Angular Validators class offers some useful validators like pattern required, minLength and maxLength. However, sometimes we require to use validate some complex values. In this type of condition, custom validators angular are very useful.
Reactive Forms in Angular lets us define custom validators very easily. In this tutorial, I am going to create confirm password validation. To do that I will be creating a separate folder by the name of must-match and keep my custom validator file there. I will name it validate-password angular .ts so it will sound generic.
must-match > validate-password.ts
import { AbstractControl } from '@angular/forms';
export class ValidatePassword {
static MatchPassword(abstractControl: AbstractControl) {
let password = abstractControl.get('password').value;
let confirmPassword = abstractControl.get('confirmPassword').value;
if (password != confirmPassword) {
abstractControl.get('confirmPassword').setErrors({
MatchPassword: true
})
} else {
return null
}
}
}
Using the Custom Validator in Reactive Form
import { FormBuilder Validators } from "@angular/forms";
import { ValidatePassword } from "./must-match/validate-password";
@Component({
//...
})
export class AppComponent {
registrationForm = this.fb.group({
PasswordValidation: this.fb.group({
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
},{
validator: ValidatePassword.MatchPassword // custom validation
})
})
}
Thanks For Sharin With Us.It gave me a lot of Helpful information.
ReplyDeleteAngular JS Online training
Angular JS training in hyderabad
thanks
Deletethanks
ReplyDelete