Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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