Open In App

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.



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:



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:




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 { }

app.component.ts:




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, }$/)])
        }
    );
}

 app.component.html:




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

Output: Hence, we have successfully triggered form validations.


Article Tags :