Last active
May 10, 2019 20:00
-
-
Save wesleygrimes/f5bdf06c5c85fd3c8cb849111b5b3de2 to your computer and use it in GitHub Desktop.
Angular - Pure vs Impure Validator Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// impure function: (this.allowedStates may return undefined) | |
private validState(): ValidatorFn { | |
return (control: AbstractControl): { [key: string]: any } | null => { | |
const currentState = control.value; | |
const foundState = this.allowedStates.find(state => currentState === state); | |
return foundState ? null : { state: 'State not allowed' }; | |
}; | |
} | |
// pure function | |
private validState(allowedStates: string[]): ValidatorFn { | |
return (control: AbstractControl): { [key: string]: any } | null => { | |
const currentState = control.value; | |
const foundState = allowedStates.find(state => currentState === state); | |
return foundState ? null : { state: 'State not allowed' }; | |
}; | |
} | |
// construct the form and attach the validator | |
... | |
allowedStates = ['FL','CA','NC']; | |
... | |
buildForm() { | |
this.form = this.fb.group({ | |
state: ['', this.validState(this.allowedStates)], | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment