Skip to content
Related Articles

Related Articles

Improve Article
How to trigger Form Validators in Angular2 ?
  • Last Updated : 28 Jul, 2020

In Angular 2, the best way to deal with complex forms is by using Reactive forms. Below we are going to elaborate on how to trigger form validators for login page.

In reactive forms, we use FormControl and by using this, we get access to sub-fields of form and their properties. Some of their properties are dirty, touched, untouched, pristine, valid, errors and etc. Using these properties, we can actually trigger validations according to the requirement.

  • Dirty: This property gets activated if the user changes the value of the sub-field from the default value.
  • Touched: If the user visits the subfield then the touched property value is set to “true”.
  • Untouched: If the user doesn’t visit the subfield then untouched property value is set to “true”. It is completely opposite to touched property.
  • Pristine: If the user visits the sub-field and doesn’t make any change in its value then it is set to “true”.
  • Valid: If the form fulfills all the form validations then it will be “true”.
  • Errors: Angular on client-side generates a list of errors that contain all the inbuilt errors like required, maxLength, pattern, minLength, etc.

Using the above-discussed properties, we can trigger the form validations with custom messages. Using the FormControl of every sub-field and checking its properties like touched, dirty and etc, we can validate the form according to the need.


  • First, add all the form controls in the component.ts file according to the .html file.
  • Then add validations in component.ts file for the required subfields, Example: Required, Max Length, Pattern, etc. 
  • Make sure you imported everything from Validators from ‘angular@/forms’
  • Then add validation messages in.html file which is demonstrated in the below code.
  • Also, import all the dependencies from ‘angular@/material’ in the module file.

For better animations and styling angular provides Angular material which has abundant information regarding the styling. Using angular material, the form is styled. Hence, we are using tags like <mat-form-field>, <mat-error>, <mat-label> and matInput.

We can import from angular material after installing it using npm. The command for importing it is mentioned below:

ng add @angular/material

Code Implementation: Below is the implementation of the above approach.



import { BrowserModule } from 
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from 
import { FormsModule, ReactiveFormsModule } 
        from '@angular/forms';
import { MatInputModule } from 
import { MatDialogModule } from 
import { MatFormFieldModule } from 
import { MatIconModule } from 
    declarations: [
    imports: [
    bootstrap: [AppComponent]
export class AppModule { }



import { Component, OnInit } 
        from '@angular/core';
// Imports
import { FormGroup, FormControl, 
    Validators } from '@angular/forms';
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
export class AppComponent implements OnInit {
    constructor() { }
    ngOnInit() {
    profile = new FormGroup(
            // Setting Validation Controls
            email: new FormControl(''
/^\w+@[a-z0-9A-Z_]+?\.[a-zA-Z]{2, 5}$/)]),
                password: new FormControl(''
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8, }$/)])



<div class="container-fluid">
  <div class="row">
    <div class="col-12 col-sm-6 
              col-md-6 col-lg-12">
      <h4>Login to start</h4>
      <form [formGroup]="profile">
        <mat-form-field appearance="outline">
          <input type="email" matInput 
            placeholder="Enter Email" 
          <mat-error *ngIf=
"profile.controls['email'].errors?.pattern && profile.controls['email'].touched">
            Enter a valid email with 
            requested pattern
          <mat-error *ngIf=
"profile.controls['email'].errors?.minLength && profile.controls['email'].touched">
            Email should have minimum 
            8 characters
          <mat-error *ngIf=
"profile.controls['email'].errors?.required && profile.controls['email'].touched">
            Email is required
        <mat appearance="outline">
          <input matInput type="password" 
            placeholder="Enter password" 
          <mat-error *ngIf=
"profile.controls['password'].errors?.required && profile.controls['password'].touched">
            Password is required
          <mat-error *ngIf=
"profile.controls['password'].errors?.minLength && profile.controls['password'].touched">
            Enter a password with 
            more than 8 letters
          <mat-error *ngIf=
"profile.controls['password'].errors?.pattern && profile.controls['password'].touched">
            Enter a password with 
            valid pattern
        </mat - form - field>
        <button class="btn btn-primary" 

Output: Hence, we have successfully triggered form validations.

My Personal Notes arrow_drop_up
Recommended Articles
Page :