Angular Material Form Validation

Angular Material Form Validation
Techiio-author
Written by Sagar RabidasJanuary 12, 2022
8 min read
Angular
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

In this blog, we will discuss Angular Material Form Validation

Angular Material Form Validation:-

In Angular material, we have a module present already which can be used to create the form quickly, but to apply any kind of validation we have to follow the traditional approaches which are basically of two types. So we can combine the material module to create the forms and validation by using either of the two approaches we have, material in the build module will help us to build the forms quickly with all the fields with default tying and animation. We have to just simply put the components inside the inbuild material library, after any of the validation approaches we can choose.

Syntax of Angular Material Form Validation

As we know that this is something that is not present inside the material library, but still we have a module that helps us to create our forms easily.

<form [formGroup]="form name" (ngSubmit)="your method">
<mat-card-content>
<mat-form-field>
<input matInput type="text" formControlName="field name" id="name">
</mat-form-field>
</mat-card-content>
</form>

As you can see in the above syntax we are trying to use ‘form group’ with the name of the form and using ‘mat-form-field’ to create our form to take the user input.

How does Form Validation work in Angular Material?

In angular, we've got unique processes that may be used to implement the form validation. Why form validation is needed? The shape is used to take the entry from the person, but the consumer can input any incorrect values that can affect the commercial enterprise common sense of our utility. For that, we need to have shape validation in place, which improves the data which wishes to be entered with the aid of the person. Permit’s take an instance where builders have requested the consumer to enter his/her phone variety but mistakenly they have supplied some strings with it. So that you can validate the consumer information on the patron degree only we require form validation.

In angular, we have two different approaches that are template-driven and reactive forms both of them have their advantage and disadvantage and specific purpose when to use which one.

  • Reactive form validation: In the reactive form approach we will always have the new starter of the form if any of the changes are made, it follows an immutable and explicit approach to validate the form. To use this inside the application we have to import a few modules from the angular library.
  • ReactiveFormsModule: This module needs to be imported and present inside the component module in which we want to implement this. If we forgot this error will occur and the code will not work.

Code:

import { ReactiveFormsModule } from '@angular/forms';
  • Now in the component file import the blow packages.

Code:

import { FormControl, FormGroup, Validators } from '@angular/forms';
  • In angular material, we have different selectors present which can be used to show our error messages.
  • mat-error: This is used to show the error, with the message attached to it. If the form is invalid then this message will appear on the screen in red color.

Syntax:

<mat-error *ngIf="your condition">Error message</mat-error>
  • In angular, we can also show hints to the user using the below selector from the mat-form-field module.
  • mat-hint: This is used to show the hint to the user if they are entering something wrong. With the hint message attached to it.

Syntax:

<mat-hint >Hint Message</mat-hint>

Example of Angular Material Form Validation

Given below is the example mentioned:

  • index.html code:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<demo-validation'>loading</demo-validation'
  • demo-validation.component.ts code:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'demo-validation',
templateUrl: './demo-validation.component.html',
styleUrls: [ './demo-validation.component.css' ] })
export class AppValidationComponent implements OnInit {
public myForm: FormGroup;
constructor() { }
ngOnInit() {
this.myForm = new FormGroup({
myName: new FormControl('', [Validators.required, Validators.maxLength(20)]),
myAddress: new FormControl('', [Validators.required, Validators.maxLength(50)]),
mycity: new FormControl('', [Validators.required, Validators.maxLength(10)])
});
}
public myError = (controlName: string, errorName: string) =>{
return this.myForm.controls[controlName].hasError(errorName);
}
}
  • demo-validation.component.html code:
<h4><u><i> Form Validation using Angular Material !!</i></u></h4>
<form [formGroup]="myForm" novalidate fxLayout="column wrap" fxLayoutAlign="center center" fxLayoutGap="10px">
<mat-card-content>
<mat-form-field>
<input matInput type="text" placeholder="Enter Name" formControlName="myName" id="myName">
<mat-hint align="end">Not more then 20 characters long.</mat-hint>
<mat-error *ngIf="myError('myName', 'required')">Name is required</mat-error>
<mat-error *ngIf="myError('myName', 'maxlength')">Limit exceed</mat-error>
</mat-form-field>
</mat-card-content>
<br />
<mat-card-content>
<mat-form-field>
<input matInput type="text" placeholder="Enter Address" formControlName="myAddress" id="myAddress">
<mat-hint align="end">Not more then 50 characters long.</mat-hint>
<mat-error *ngIf="myError('myAddress', 'required')">Address is required</mat-error>
<mat-error *ngIf="myError('myAddress', 'maxlength')">Limit exceed</mat-error>
</mat-form-field>
</mat-card-content>
<br/>
<mat-card-content>
<mat-form-field>
<input matInput type="text" placeholder="Enter City" formControlName="mycity" id="myAddress">
<mat-hint align="end">Not more then 10 characters long.</mat-hint>
<mat-error *ngIf="myError('mycity', 'required')">City is required</mat-error>
<mat-error *ngIf="myError('mycity', 'maxlength')">Limit exceed</mat-error>
</mat-form-field>
</mat-card-content>
</form>
  • module.ts code:
import {NgModule} from '@angular/core';
import {MatFormFieldModule} from '@angular/material/form-field';
@NgModule({
exports: [
MatFormFieldModule
] })
export class MaterialValidationModule {}
  • demo-validation.module.ts code:
import { NgModule } from "@angular/core"// other importsa
import { FormsModule } from "@angular/forms";
import { ReactiveFormsModule } from '@angular/forms';
import { AppValidationComponent } from "./app.component";@NgModule({
imports: [FormsModule, ReactiveFormsModule],
declarations: [AppValidationComponent],
bootstrap: [AppValidationComponent] })
export class AppValidationModule {}

Angular
AngularJs
Angular Material
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance