Hello Devs,
In this tutorial, we are going to learn how to create custom validators in angular 10.
Custom validation is the most important thing in a programming language. most of the cases and most of the project you need to create some custom validation so you can reuse it and also write septate code on file then you can use it as like pre-defined validation.
Follow this step by step guide given below:
Install Angular App
ng new my-custom-val-app
Import FormsModule
src/app/app.module.ts
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 { }
Form with ngModel
src/app/app.component.html
<h1>How to Create Custom Validators in Angular 10 - Rathorji.in</h1>
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="username">Username</label>
<input
formControlName="username"
id="username"
type="text"
class="form-control">
<div *ngIf="f.username.touched && f.username.invalid" class="alert alert-danger">
<div *ngIf="f.username.errors.required">Username is required.</div>
<div *ngIf="f.username.errors.minlength">Username should be 3 character.</div>
<div *ngIf="f.username.errors.cannotContainSpace">Username can not contain space.</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
formControlName="password"
id="password"
type="password"
class="form-control">
<div *ngIf="f.password.touched && f.password.invalid" class="alert alert-danger">
<div *ngIf="f.password.errors.required">Password is required.</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
updated Ts File
src/app/app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { UsernameValidator } from './username.validator';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
form = new FormGroup({
username: new FormControl('', [Validators.required, Validators.minLength(3), UsernameValidator.cannotContainSpace]),
password: new FormControl('', Validators.required)
});
get f(){
return this.form.controls;
}
submit(){
console.log(this.form.value);
}
}
Create Custom Validation File
src/app/username.validator.ts
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class UsernameValidator {
static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
if((control.value as string).indexOf(' ') >= 0){
return {cannotContainSpace: true}
}
return null;
}
}
Run this command:
ng serve
I hope this example helps you.