问题
I am trying to validate password and repeat password in a form. Like this
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
this.registerForm = fb.group({
name: ['', Validators.required],
email: ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"), Validators.required])],
passwords: this.fb.group({
password: ['', Validators.compose([Validators.required])],
repassword: ['', Validators.compose([Validators.required])]
}, this.comparePassword)
});
function comparePassword(c: AbstractControl) {
return c.get('password').value === c.get(' repassword').value
}
** I also tried passing return false in comparePassword as:
comparePassword(c: AbstractControl) {
return false;
}
** but every time console.log(this.registerForm.valid); gives me true, but it should return false if i am giving different inputs in password and repeatpassword. So please help how to resolve this. Thanks in advance
回答1:
A strange thing: custom validation should return null
when valid.
If the validation fails you should return a validation error { "comparePassword": true }
So I think your function should be:
comparePassword(control: AbstractControl) {
if(control.get('password').value === control.get('repassword').value){
return null;
}
return { “comparePassword”: true };
}
Angular.io Custom validation: That function takes an Angular control object and returns either null if the control value is valid or a validation error object. The validation error object typically has a property whose name is the validation key, 'forbiddenName', and whose value is an arbitrary dictionary of values that you could insert into an error message ({name}).
回答2:
This should work
comparePassword = (control: AbstractControl): {[key: string]: boolean} => {
// get values
const password = control.get('password');
const repassword = control.get('repassword');
// if no values, validated as true
if (!password || !repassword) {
return null;
}
// if values match, return null, else nomatch: true
return password.value === repassword.value ? null : { nomatch: true };
};
and then in your build of form, set:
{validator: this.comparePassword}
in
this.registerForm = fb.group({
name: ['', Validators.required],
email: ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"), Validators.required])],
passwords: this.fb.group({
password: ['', Validators.compose([Validators.required])],
repassword: ['', Validators.compose([Validators.required])]
},{validator: this.comparePassword}) // here
});
来源:https://stackoverflow.com/questions/43887201/repeat-password-validation-not-working