Angular Material Form Group Validation Dynamic Error Messages

Updated on: May 27, 2021

There are various ways to show the Validation error messages on the form, In Angular, if you are using Angular Material as UI tool and you wan to show the Form Validation message, then follow the below steps to add Angular Material Form Group Validation and show validation error messages on the web page dynamically as you start typing:

Step 1: Install Angular material using following command in your project, it will add required changes to package.json & angular.json files: 

ng add @angular/material

Step 2: Add the following required Modules into app.module.ts configuration file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MatInputModule } from '@angular/material/input';

Add the following imports in the @NgModule imports declaration.

imports:      [ BrowserModule, FormsModule, ReactiveFormsModule, BrowserAnimationsModule, MatInputModule ],

Step 3: Add the following CSS file path in angular.json file in builld=>Styles declaration if it is not already added. If you miss adding this CSS file path, then it will not display the textbox properly.

 "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",

Step 4: Add the following code to add validation code at component level in your app.component.ts file as shown below:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})


export class AppComponent  implements OnInit {
  title = 'MyShopApp';
  public addShopFormGroup: FormGroup;
  constructor() { }
  ngOnInit() {
    this.addShopFormGroup = new FormGroup({
      shopName : new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(20)]),
      shopAddress : new FormControl('', [Validators.required, Validators.maxLength(200)])
    });
  }
  public checkError = (controlName: string, errorName: string) => {
    return this.addShopFormGroup.controls[controlName].hasError(errorName);
  }
}

Step 5: Add the following html template code to display Angular Material Form:

<div style="margin-left:20px;">
<h3>Add New Shop</h3>
<div class="example-container">
  <form [formGroup]="addShopFormGroup"  (ngSubmit)="onSubmit()" class="example-form">
    <p>
        <mat-form-field appearance="outline" class="example-full-width">
          <mat-label>Shop Name</mat-label>
          <input matInput [ngModel]="shopName" formControlName="shopName" >
          <mat-error *ngIf="checkError('shopName', 'required')">Shop Name is required</mat-error>
          <mat-error *ngIf="checkError('shopName', 'minlength')">Shop Name should be more than 5 characters</mat-error>
          <mat-error *ngIf="checkError('shopName', 'maxlength')">Shop Name should be less than 20 characters</mat-error>
        </mat-form-field>
      </p>
      <p>
          <mat-form-field appearance="outline" class="example-full-width">
            <mat-label>Shop Address</mat-label>
                <textarea matInput  formControlName="shopAddress"></textarea>
                <mat-error *ngIf="checkError('shopAddress', 'required')">Shop Address is required</mat-error>
                <mat-error *ngIf="checkError('shopAddress', 'maxlength')">Shop Address should be less than 200 characters</mat-error>
          </mat-form-field>
        </p>      
        <p>
          <img mat-card-sm-image >
        </p>         
    <button type="submit" [disabled]="!addShopFormGroup.valid" >Submit</button>
  </form>
  </div>
</div>

If you see from the above form html code, we have added validation for required, minlength & maxlength. It will show validation error message whenever it fails the validation. This validation check happens dynamically when you start typing values in the form controls. Also you can disable the form submit button, it will only get enabled when entire form is validated.

You can try above Angular Material Form Group Vaidation, for output and sample code demonstration visit: https://stackblitz.com/edit/angular-material-form-group-validation