Issue
I am trying to add custom validation in angular for password and confirm password :
<div class="col form-group mx-2 my-2">
<label class="mb-1" for="password">Password</label>
<input type="password" id="password" name="password" class="form-control"
[class.is-invalid]="form['password'].invalid && form['password'].touched" formControlName="password"
placeholder="Enter Password">
<div *ngIf="form['password'].touched && form['password'].invalid" class="text-danger">
<small *ngIf="form['password'].errors?.['required']">Password is Required</small>
<small *ngIf="form['password'].errors?.['minlength']">Password must be at least 5 Characters</small>
</div>
</div>
<div class="col form-group mx-2 my-2">
<label class="mb-1" for="confirmPassword">Confirm Password</label>
<input type="password" id="confirmPassword" name="confirmPassword" class="form-control"
[class.is-invalid]="form['confirmPassword'].errors && form['confirmPassword'].touched"
formControlName="confirmPassword" placeholder="Enter Confirm Password">
<div *ngIf="form['confirmPassword'].errors && form['confirmPassword'].touched" class="text-danger">
<small *ngIf="form['confirmPassword'].errors['required']">Confirm Password is Required</small>
<small *ngIf="form['confirmPassword'].errors['matching']">Passwords do not match</small>
</div>
</div>
Solution
You can create custom validation for password and confirm password like this :
//password.validator.ts
import { AbstractControl, FormGroup, ValidatorFn } from "@angular/forms";
export default class Validation {
static match(controlName: string, checkControlName: string): ValidatorFn {
return (controls: AbstractControl) => {
const control = controls.get(controlName);
const checkControl = controls.get(checkControlName);
if (checkControl?.errors && !checkControl.errors['matching']) {
return null;
}
if (control?.value !== checkControl?.value) {
controls.get(checkControlName)?.setErrors({ matching: true });
return { matching: true };
} else {
return null;
}
};
}
}
then add that validation
//register.component.ts
import Validation from './password.validator';
this.registerForm = this.fb.group({
password: ['', [Validators.required, Validators.minLength(5)]],
confirmPassword: ['', Validators.required]
}, { validators: [Validation.match('password', 'confirmPassword')] } )
to your .ts file after the formgroup like this and use it the way you have mentioned
Answered By - Rohit Kharche
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.