Created
April 30, 2021 22:17
-
-
Save inorganik/8ee396a4af370bc494b7753a98e2a22f to your computer and use it in GitHub Desktop.
Angular validators
This file contains hidden or 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
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