Angular FormControl Validators
January 13, 2021
Angular FormControl
validators are provided by Angular Validators
class. The Validators
class provides a set of built-in 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.
Contents
Technologies Used
Find the technologies being used in our example.1. Angular 11.0.3
2. Node.js 12.5.0
3. NPM 6.9.0
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>
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>
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>
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>
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>
Run Application
To run the application, find the steps.1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.

References
Angular FormControlAngular Validators