Angular FormControl Validators
January 15, 2024
Angular FormControl
validators are provided by Validators
class that has a set of built-in sync validators such as min
, max
, required
, email
, minLength
, maxLength
and pattern
. The FormControl
provides properties to check validation status. These properties are status
, valid
, invalid
, disabled
, pristine
, dirty
, touched
, untouched
etc.
1. We can validate
FormControl
using sync validators and async validators with following syntax.
FormControl(<value>, [<sync validator>], [<async validator>])
2. Find the syntax when we use only sync validators.
FormControl(<value>, [<sync validator>])
3. Find the syntax when we use only async validators.
FormControl(<value>, [], [<async validator>])
Here on this page, I will provide examples to use sync and async validators to use with
FormControl
.
Contents
1. minlength and maxlength Validation
Find theValidators.minLength
and Validators.maxLength
with FormControl
.
Component code:
username = new FormControl('', [Validators.minLength(5), Validators.maxLength(10)]);
<input [formControl]="username"> <div *ngIf="username.hasError('minlength')"> Minimum length should be 5. </div> <div *ngIf="username.hasError('maxlength')"> Maximum length should be 10. </div>
2. required Validation
Find theValidators.required
with FormControl
.
Component code:
company = new FormControl('', [Validators.required]);
<input [formControl]="company"> <div *ngIf="company.hasError('required')"> Name required. </div>
3. email Validation
Find theValidators.email
with FormControl
.
Component code:
primaryEmail = new FormControl('', [Validators.email]);
<input [formControl]="primaryEmail"> <div *ngIf="primaryEmail.hasError('email')"> Email not valid. </div>
4. pattern Validation
Find theValidators.pattern
with FormControl
.
Component code:
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; secondaryEmail = new FormControl('', [Validators.pattern(this.emailPattern)]);
<input [formControl]="secondaryEmail"> <div *ngIf="secondaryEmail.hasError('pattern')"> Email not valid. </div>
5. min and max Validation
Find theValidators.min
and Validators.max
with FormControl
.
Component code:
age = new FormControl('', [Validators.min(18), Validators.max(50)]);
<input [formControl]="age"> <div *ngIf="age.hasError('min')"> Minimum age should be 18. </div> <br/> <div *ngIf="age.hasError('max')"> Maximum age should be 50. </div>
6. Using Async Validators
Here I will create a custom async validator to validate an invalid mobile number.import { AbstractControl, AsyncValidatorFn } from '@angular/forms'; import { ValidationErrors } from '@angular/forms'; import { Observable, of } from 'rxjs'; export function invalidMobNumValidator(): AsyncValidatorFn { return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => { if (control.value.startsWith('91')) { return of(null); } else { return of({ "invalidMobNum": true }); } }; }
FormGroup
instance, create a FormControl
and pass the array of async validators at third argument place of the FormControl
.
customerForm = this.formBuilder.group({ mobNum: ['', [Validators.required], [invalidMobNumValidator()]] });
<input formControlName="mobNum"> <div *ngIf="customerForm.get('mobNum')?.hasError('invalidMobNum')" ngClass="error"> Enter valid number. </div>
7. Output
Find the print-screen of the output.8. References
Angular FormControlAngular Validators