Reputation: 201
I am trying to add an asynchronous validation to form level (for cross-field validation). But the validation function is not getting triggered. Is it Possible to add Async Validation in Form Level? Or what is wrong with my validation?
// my form
creatForm(): void {
this.registerForm = this.fb.group({
firstName: [null, [Validators.required, Validators.minLength(3), Validators.maxLength(15)]],
lastName: [null, [Validators.required, Validators.minLength(3), Validators.maxLength(15)]],
phone: [null,
[Validators.required, Validators.minLength(10), Validators.maxLength(10)],
[this.phoneValidity.checkPhoneValidity()]],
email: [null,
[Validators.required, Validators.email],
[this.emailValidity.checkEmailValidity()]],
password: [null, [Validators.required, Validators.minLength(3), Validators.maxLength(15)]],
rePassword: [null, [Validators.required]]
}, { /*validators: [PasswordRePasswordValidator],*/ asyncValidators: [PasswordRePasswordValidator]});
}
//my validator
export function PasswordRePasswordValidator(control: FormGroup): Observable<ValidationErrors | null> {
const password = control.get('password').value;
const rePassword = control.get('rePassword').value;
console.log('password', password);
console.log(rePassword);
let v: Observable<ValidationErrors | null>;
return v = new Observable(observer => {
if (password && rePassword) {
console.log('password exists');
if (password === rePassword) {
observer.next(null);
observer.complete();
} else {
setTimeout(() => {
observer.next({unMatchPassword : 'Password Doesn\'t Match'});
observer.complete();
}, 1500);
}
} else {
console.log('password isnt exists')
observer.next(null);
observer.complete();
}
});
}
Upvotes: 1
Views: 700
Reputation: 11
In order to validate password and confirm password u can just use small trick. Set pattern for confirm password input with password value. Then its automatically validates .
<input formControlName=“password” />
<input formControlName=“confirmPassword” [pattern]=“form.get(‘password’).value” />
Upvotes: 1