How to trigger Form Validators in Angular2 ?

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.

Approach:

  • 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.

app.module.ts:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import { BrowserModule } from 
        '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from 
        '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } 
        from '@angular/forms';
import { MatInputModule } from 
        '@angular/material/input';
import { MatDialogModule } from 
        '@angular/material/dialog';
import { MatFormFieldModule } from 
        '@angular/material/form-field';
import { MatIconModule } from 
        '@angular/material/icon';
  
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        MatInputModule,
        MatFormFieldModule,
        MatIconModule,
        MatDialogModule,
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

chevron_right


app.component.ts:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component, OnInit } 
        from '@angular/core';
  
// Imports
import { FormGroup, FormControl, 
    Validators } from '@angular/forms';
  
  
@Component({
    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(''
                [Validators.required, 
                Validators.minLength(8),
                Validators.pattern(
/^\w+@[a-z0-9A-Z_]+?\.[a-zA-Z]{2, 5}$/)]),
                password: new FormControl(''
                [Validators.required, 
                Validators.minLength(8),
                Validators.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8, }$/)])
        }
    );
}

chevron_right


 app.component.html:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<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">
          <mat-label>Email</mat-label>
          <input type="email" matInput 
            placeholder="Enter Email" 
            formControlName="email">
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.pattern && profile.controls['email'].touched">
            Enter a valid email with 
            requested pattern
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.minLength && profile.controls['email'].touched">
            Email should have minimum 
            8 characters
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.required && profile.controls['email'].touched">
            Email is required
          </mat-error>
        </mat-form-field>
  
        <mat appearance="outline">
          <mat-label>Password</mat-label>
          <input matInput type="password" 
            placeholder="Enter password" 
            formControlName="password">
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.required && profile.controls['password'].touched">
            Password is required
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.minLength && profile.controls['password'].touched">
            Enter a password with 
            more than 8 letters
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.pattern && profile.controls['password'].touched">
            Enter a password with 
            valid pattern
          </mat-error>
        </mat - form - field>
  
        <button class="btn btn-primary" 
          [disabled]="!profile.valid"> 
          Submit
        </button>
      </form>
    </div>
  </div>
</div>

chevron_right


Output: Hence, we have successfully triggered form validations.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.