Table of Contents
Learning Objective
- How to use all angular built-in validator in a reactive form.
Built-in Validators
Angular built-in validators won’t always match the exact use case of your application. so you can create your own custom validator. I would recommend reading this article: Angular Custom Validator
List of built-in validators:
- required
- requiredTrue
- min
- max
- minLength
- maxLength
- pattern,
- nullValidator
- compose
At the time of writing this article, I am using angular version: 6.1.0. But most of the validators are available after 4.2.0.
We’ll be using the following files throughout this example:
demo-form.component.html
demo-form.component.ts
demo-form.component.ts
will look as follows, It doesn’t contain any validators right now, but we’ll add it one by one<br />import { Component, OnInit } from '@angular/core';<br />import { FormBuilder, FormGroup,Validators, } from '@angular/forms';<br /><br />@Component({<br /> selector: 'app-demo-form',<br /> templateUrl: './app-demo-form.component.html',<br /> styleUrls: ['./app-demo-form.component.scss'],<br />})<br /><br />export class DemoFormComponent implements OnInit {<br /> form: FormGroup;<br /> submitted:boolean=false;<br /><br /> constructor(private fb: FormBuilder) { }<br /><br /> ngOnInit() {<br /> this.form = this.fb.group({<br /> name: ['']<br /> });<br /> }<br /> <br /> onSubmit() {<br /> this.submitted=true;<br /> }<br />}<br />
and demo-form.component.html
will look as follows:
<br /><div><br /> <h2>Angular Reactive Form Validation</h2><br /> <form [formGroup]="form" (ngSubmit)="onSubmit()"><br /> <div><br /> <label>Name</label><br /> <input type="text" formControlName="name" /><br /> </div><br /> <div><br /> <button>Register</button><br /> </div><br /> </form><br /></div><br />
Now we’ll add all validators one by one to the demo form.
1) required
This validator will set required property to true to the form-control instance if validation fails.
The thing we’ll implement to understand required
validator:
- name field is required
To make the name field as required, we’ll add required
validator to the form.
<br />this.form = this.fb.group({<br /> name: ['', Validators.required]<br /> });<br />
demo-form.component.html
, we’ll add validation as following to the input element to show the error if input element invalid.
<br /> <div class="error" *ngIf="form.get('name').hasError('required') && submitted">Name is required</div><br /> <br />
Above code will check two conditions:
1. The input element value is empty.
2. The form is submitted.
If both conditions are true, then it will show the error otherwise, it won’t show the error.
You can see that we have used get('name')
method of form-group to get the control of the input element.
and we’ve also used hasError('required')
method to check that required error is exist or not for that control because angular will set required
property to true to the element when validation fails.
We have also checked submitted
variable to check that form has been submitted or not.
demo-form.component.html
will look as follow after adding required validators to all fields:
<br /><div><br /> <h2>Angular Reactive Form Validation</h2><br /> <form [formGroup]="form" (ngSubmit)="onSubmit()"><br /> <div><br /> <label>Name</label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('required') && submitted">Name is required</div><br /> </div><br /> <div><br /> <button [disabled]="form.invalid">Register</button><br /> </div><br /> </form><br /></div><br />
2) requiredTrue
Validator that requires the control’s value be true. This validator is commonly used for required checkboxes i.e accept terms and conditions checkbox.
This validator also set required
property to true to the form-control instance if validation fails.
To understand requiredTrue, we’ll add a new field called Accept Terms and Conditions, which will be a checkbox.
so our demo-form.component.ts
will look as follows:
this.form = this.fb.group({<br /> name: ['', Validators.required],<br /> tnc:['',Validators.requiredTrue]<br /> });<br /><br />
and demo-form.component.html
file will look as follows:
<div><br /> <h2>Angular Reactive Form Validation</h2><br /> <form [formGroup]="form" (ngSubmit)="onSubmit()"><br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('required') && submitted">Name is required</div><br /> </div><br /> <div> <br /> <label>Accept Term and Conditions :</label><br /> <input type="checkbox" formControlName="tnc" /><br /> <div class="error" *ngIf="form.get('tnc').hasError('required') && submitted">You must agree to the terms and conditions </div><br /> </div><br /> <div><br /> <button>Register</button><br /> </div><br /> </form><br /></div>
If you will click on Register button it will highlight all the errors.
3) email
email
property to true to the form-control instance if validation fails.email
and we’ll add two validation to it.- required validation
- email validation
compose
validator function which accepts an array of validators.<br />email:['',Validators.compose([Validators.required,Validators.email])]<br />
demo-form.component.ts
will look as follows:<br />this.form = this.fb.group({<br /> email:['',Validators.compose([Validators.required,Validators.email])]<br /> });<br />
demo-form.component.html
will look as follows:<br /> <div><br /> <label>Email: </label><br /> <input type="email" formControlName="email" /><br /> <div class="error" *ngIf="form.get('email').hasError('required') && submitted">Email is required</div><br /> <div class="error" *ngIf="form.get('email').hasError('email') && form.get('email').touched">Email is invalid</div><br /> </div><br />
4) min
quantity
field.- Minimum required quantity is 10.
demo-form.component.ts
will look as follows:<br />this.form = this.fb.group({<br /> quantity:['',Validators.min(10))]<br /> });<br />
demo-form.component.html
will look as follows:<br /> <div><br /> <label>Quantity: </label><br /> <input type="number" formControlName="quantity" /><br /> <div class="error" *ngIf="form.get('quantity').hasError('min') && submitted">Minimum required quantity is 10</div><br /> </div><br />
<br /> <div><br /> <label>Quantity: </label><br /> <input type="number" formControlName="quantity" /><br /> <div class="error" *ngIf="form.get('quantity').hasError('min') && submitted">Maximum required quantity is {{form.get('quantity').errors?.min?.min}}</div><br /> </div>
5) max
quantity
field.- Maximum required quantity is 50.
demo-form.component.ts
will look as follows:<br />this.form = this.fb.group({<br /> quantity:['',Validators.max(50))]<br /> });<br />
demo-form.component.html
will look as follows:<br /> <div><br /> <label>Quantity: </label><br /> <input type="number" formControlName="quantity" /><br /> <div class="error" *ngIf="form.get('quantity').hasError('max') && submitted">Maximum required quantity is 50</div><br /> </div><br />
<br /> <div><br /> <label>Quantity: </label><br /> <input type="number" formControlName="quantity" /><br /> <div class="error" *ngIf="form.get('quantity').hasError('max') && submitted">Maximum required quantity is {{form.get('quantity').errors?.max?.max}}</div><br /> </div><br />
6) minLength
minLength
validator:minLength
validators to name
property as follows:<br />this.form = this.fb.group({<br /> name:['',Validators.minLength(5))]<br /> });<br />
and demo-form.component.html
will look as follows:
<br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('minlength') && submitted">Name must be at least 5 characters long.</div><br /> </div><br />
minLength
from reactive form,we can update
demo-form.component.html
as follows:
<br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('minlength') && submitted"> Name must be at least {{form.get('name').errors?.minlength?.requiredLength}} characters long.</div> <br /> </div>
7) maxLength
maxLength
validator:maxLength
validators to name property as follows:<br />this.form = this.fb.group({<br /> name:['',Validators.maxLength(5))]<br /> });<br />
demo-form.component.html
will look as follows:<br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('maxlength') && submitted">Name can be max 12 characters long.</div><br /> </div><br />
maxLength
from reactive form, we can updatedemo-form.component.html
as follows:
<br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('name').hasError('maxlength') && submitted"> Name can be max {{form.get('name').errors?.maxlength?.requiredLength}} characters long.</div> <br /> </div>
8) pattern
pattern
validation, we’ll take an example of username
property.<br />this.form = this.fb.group({<br /> username:['',Validators.pattern(
"^[a-z0-9_-]{8,15}$"))]
});
demo-form.component.html
will look as follows:<br /> <div><br /> <label>Name: </label><br /> <input type="text" formControlName="name" /><br /> <div class="error" *ngIf="form.get('username').hasError('pattern') && submitted">Username is invalid</div> </div><br />
9) nullValidator
10) compose
maxLength
and minLength
validator as follows:<br />this.form = this.fb.group({<br />
username:['',Validators.compose([Validators.minLength(5),Validators.maxLength(12)])]
});
demo-form.component.html
will look as follows:
<br /><div><br /> <label>Username: </label><br /> <input type="text" formControlName="username" /><br /> <div class="error" *ngIf="form.get('name').hasError('minlength') && submitted"> Name must be at least {{form.get('name').errors?.minlength?.requiredLength}} characters long.</div> <br /> <div class="error" *ngIf="form.get('name').hasError('maxlength') && submitted"> Name can be max {{form.get('name').errors?.maxlength?.requiredLength}} characters long.</div> <br /> </div>
And that’s it, that’s all the built-in validators are.
Thanks for reading the article.
Also, read: