Skip to content

Instantly share code, notes, and snippets.

@wesleygrimes
Last active May 10, 2019 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleygrimes/f5bdf06c5c85fd3c8cb849111b5b3de2 to your computer and use it in GitHub Desktop.
Save wesleygrimes/f5bdf06c5c85fd3c8cb849111b5b3de2 to your computer and use it in GitHub Desktop.
Angular - Pure vs Impure Validator Functions
// 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