Categories

Monday, January 17, 2022
therichposts@gmail.com
Angular 12MaterialAngular

Angular Material Form Validation Working Example Code

Angular Material Form Validation Working Example Code

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Angular Material Form Validation Working Example Code.

Working Demo

Angular 12 came and if you are new then you must check below two links:

  1. Angular 12 Demos
  2. AngularMaterial

Angular Material Form Validation Working Example Code
Angular Material Form Validation Working Example Code

Friends here is the code snippet and please use this carefully to avoid mistakes:

1. Firstly friends we need fresh angular 12 setup and for this we need to run below commands but if you already have angular 12 setup then you can avoid below commands. Secondly we should also have latest node version installed on our system:

npm install -g @angular/cli

ng new angularmaterial

cd angularmaterial

ng serve --o

//Here is the url, you need to run into your browser and see working angular test project
http://localhost:4200/

2. Now friends we need to run below command into our project terminal to get angular material and its related modules:

ng add @angular/material

ng serve --o

3. Now friends we need to add below code into our project/src/app/app.module.ts file to import the angular material form fields for responsive layout and its related modules:

...
import { NgModule } from '@angular/core';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {MatIconModule} from '@angular/material/icon';



...
  imports: [
    ...
    MatFormFieldModule,
    MatInputModule,
    FormsModule
    MatIconModule,
    ReactiveFormsModule,
  ],

4. Now friends we need to add below code into our project/src/app/app.component.ts file :

import { Component, Inject } from '@angular/core';
import {FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';
/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    //condition true
    const isSubmitted = form && form.submitted;

    //false
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  /*Form*/
  unameFormControl = new FormControl('', [
    Validators.required,   
  ]);
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);
  pwdFormControl = new FormControl('', [
    Validators.required,   
    Validators.minLength(8),
  ]);  

  matcher = new MyErrorStateMatcher();
}

5. Finally friends we need to add below code into our project/src/app/app.component.html file to get the final output on web browser:

<form (ngSubmit)="Submit()">
  <mat-form-field appearance="fill">
      <mat-label>User Name</mat-label>
      <input matInput [formControl]="unameFormControl" [errorStateMatcher]="matcher" required>
      <mat-error *ngIf="unameFormControl.hasError('required')">
          Username is <strong>required</strong>
        </mat-error>
    </mat-form-field><br />
    <mat-form-field class="example-full-width" appearance="fill">
      <mat-label>Email</mat-label>
      <input type="email" matInput [formControl]="emailFormControl" [errorStateMatcher]="matcher"
             placeholder="Ex. pat@example.com" required>
      <mat-hint>Errors appear instantly!</mat-hint>
      <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
        Please enter a valid email address
      </mat-error>
      <mat-error *ngIf="emailFormControl.hasError('required')">
        Email is <strong>required</strong>
      </mat-error>
    </mat-form-field><br />
    <mat-form-field appearance="fill">
      <mat-label>Password</mat-label>
      <input matInput [formControl]="pwdFormControl" [errorStateMatcher]="matcher" required>
        <mat-error type="password" *ngIf="pwdFormControl.hasError('required')">
          Password is <strong>required</strong>
        </mat-error>
      <mat-error *ngIf="pwdFormControl.hasError('minlength') && !pwdFormControl.hasError('required')">
          Max lenght <strong>8 char</strong>
        </mat-error>       
    </mat-form-field><br />
  
    <button type="submit" mat-raised-button color="primary">Submit</button>
  </form>
  

Now we are done friends. If you have any kind of query or suggestion or requirement then feel free to comment below.

Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.

Jassa

Thanks

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular12, Angular 13, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.