Skip to content

Instantly share code, notes, and snippets.

@inorganik
Created April 30, 2021 22:17
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 inorganik/8ee396a4af370bc494b7753a98e2a22f to your computer and use it in GitHub Desktop.
Save inorganik/8ee396a4af370bc494b7753a98e2a22f to your computer and use it in GitHub Desktop.
Angular validators
import {
AbstractControl,
AsyncValidatorFn,
ValidationErrors,
ValidatorFn,
Validators,
} from '@angular/forms';
export class CustomValidators {
/**
* debounced async validator example
* (async validators are the 3rd arg in FormControl constructor)
*/
static nameValidator(existingName = ''): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => {
const val = control.value.trim();
if (!val || val === existingName) {
return of(null);
} else {
return timer(500).pipe(
switchMap(() => this.service.nameIsAvailable(val)),
map((result: boolean) => (result ? null : { nameTaken: true }))
);
}
};
}
/**
* regular custom validator
*/
static nameValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors => {
const name = control.value;
if (name.length) {
let valid = false;
// do some validation here
return valid ? null : { nameInvalid: true };
}
return null;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment