In this tutorial, we will explain to you how to create custom validation in angular 11(Angular 11 Custom Validation Tutorial with Example). In this example, we will use the reactive forms module for customized validation.
We will create a new angular app using the following command.
ng new myapp cd myapp
In this step, we need to add a module into the src/app/app.module.ts file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In this step, we have created a simple form with some fields. when we click on the submit button at that time check the validation. if validation is false then will be shown an error message.
src/app/app.component.html
<div class="container"> <h2>Angular 11 Custom Validation Tutorial with Example</h2> <form [formGroup]="form" (ngSubmit)="submit()"> <div class="form-group"> <label for="email">Email</label> <input formControlName="email" id="email" type="email" class="form-control"> <div *ngIf="validCheck.email.touched && validCheck.email.invalid" class="alert alert-danger"> <div *ngIf="validCheck.email.errors.required">Email is required.</div> <div *ngIf="validCheck.email.errors.email">Please enter a valid email.</div> </div> </div> <div class="form-group"> <label for="password">Password</label> <input formControlName="password" id="password" type="password" class="form-control"> <div *ngIf="validCheck.password.touched && validCheck.password.invalid" class="alert alert-danger"> <div *ngIf="validCheck.password.errors.required">Password is required.</div> <div *ngIf="validCheck.password.errors.minlength">Password must be at least 6 characters</div> </div> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> </div>
src/app/app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('',[ Validators.required, , Validators.minLength(6)])
});
get validCheck(){
return this.form.controls;
}
submit(){
console.log(this.form.value);
}
}
Now we will run our Angular application using the below command.
ng serve