Angular FormControl Validators

By Arvind Rai, 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>]) 
First parameter is for value, second parameter is for sync validators and third parameter is for async validators.
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>]) 
If we want to use only async validators, just keep an empty array at second parameter place.
Here on this page, I will provide examples to use sync and async validators to use with FormControl.

1. minlength and maxlength Validation

Find the Validators.minLength and Validators.maxLength with FormControl.
Component code:
username = new FormControl('', [Validators.minLength(5), Validators.maxLength(10)]); 
HTML code:
<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 the Validators.required with FormControl.
Component code:
company = new FormControl('', [Validators.required]); 
HTML code:
<input [formControl]="company"> 
<div *ngIf="company.hasError('required')"> 
    Name required. 
</div> 

3. email Validation

Find the Validators.email with FormControl.
Component code:
primaryEmail = new FormControl('', [Validators.email]); 
HTML code:
<input [formControl]="primaryEmail">
<div *ngIf="primaryEmail.hasError('email')"> 
    Email not valid.
</div> 

4. pattern Validation

Find the Validators.pattern with FormControl.
Component code:
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
secondaryEmail = new FormControl('', [Validators.pattern(this.emailPattern)]); 
HTML code:
<input [formControl]="secondaryEmail">
<div *ngIf="secondaryEmail.hasError('pattern')"> 
    Email not valid.
</div> 

5. min and max Validation

Find the Validators.min and Validators.max with FormControl.
Component code:
age = new FormControl('', [Validators.min(18), Validators.max(50)]); 
HTML code:
<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 });
    }
  };
} 
Now in 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()]]
}); 
In HTML code, display error messages as following.
<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.
Angular FormControl Validators

8. References

Angular FormControl
Angular Validators

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us