Angular FormControl Validators

By Arvind Rai, 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.

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 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 *ngIf="username.hasError('maxlength')"> 
    Maximum length should be 10.

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. 

email Validation

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

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.

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.

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.
Angular FormControl Validators


Angular FormControl
Angular Validators

Download Source Code


©2023 | Privacy Policy | Contact Us