Angular already have many built-in validators but sometimes we need some extra validation according to our project need.
Steps to create custom validators
Step 1: Create a function or class method where we can define our all custom validators.
File: src/CustomValidators.ts
import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
export class CustomValidators
constructor() {}
}
2. Define the function definition of custom validators to validate only char in input field
import { AbstractControl, ValidatorFn, FormControl } from '@angular/forms';
export class CustomValidators{
constructor() {}
static onlyChar():ValidatorFn{
return (control: AbstractControl): { [key: string]: boolean } | null => {
if(control.value=="")
return null;
let re = new RegExp("^[a-zA-Z ]*$");
if (re.test(control.value )) {
return null;
} else {
return { "onlyChar": true };
}
}
}
}
I have defined a function name onlyChar and return type is ValidatorFn, so in the definition of function i returned a inline function which accepts one parameter type of AbstractControl.
In the next expression, i a checking the value of control if its empty then i am returning null, which means no error in the control.
In next step i have defined RegExp to validate the input for Capital and lower case char only, which return onlyChar .
Let’s implement it in our FormGroup Form with validation.
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-register',
templateUrl: './<meta charset="utf-8">register.component.html',
styleUrls: ['./<meta charset="utf-8">register.component.css']
})
export class RegisterComponent implements OnInit {
form: FormGroup = new FormGroup(
{
name:new FormControl("",[Validators.required,Validators.minLength(4),CustomValidators.onlyChar()]),
email:new FormControl("",[Validators.required,Validators.email]),
password:new FormControl("",[Validators.required]),
}
);
constructor() { }
ngOnInit(): void {
}
submitForm(){
if(this.form.valid){
console.log("send request to server",this.form.value);
// send request to server
}
else{
this.form.markAllAsTouched();
console.log("Form has errors");
}
}
}
<form [formGroup]="form" (submit)="submitForm()">
<div>
Name : <input type="name" formControlName="name" placeholder="Name" /> <br>
<div *ngIf="form.controls.name.invalid && (form.controls.name.dirty || form.controls.name.touched)"
class="alert alert-danger">
<div *ngIf="form.controls.name.errors?.required">
Name is required.
</div>
<div *ngIf="form.controls.name.errors?.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="form.controls.name.errors?.onlyChar">
Name only contain characters.
</div>
</div>
</div>
<div>
Email : <input type="email" formControlName="email" placeholder="Email" /> <br>
<div *ngIf="form.controls.email.invalid && (form.controls.email.dirty || form.controls.email.touched)"
class="alert alert-danger">
<div *ngIf="form.controls.email.errors?.required">
Email is required.
</div>
<div *ngIf="form.controls.email.errors?.email">
Enter valid email
</div>
</div>
</div>
<div>
Password : <input type="password" formControlName="password" placeholder="Password" /> <br>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
Output:
Check this example and code for custom validation