我有表格:
this.changePasswordForm = this.formBuilder.group({
'passwordNew': ['', ValidationService.passwordValidator], matchingPasswords('passwordNew', 'passwordNewConfirmation')(this)]]
});
我尝试调用的自定义验证函数:
export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
return (group: FormGroup): {
[key: string]: any
} => {
let password = group.controls[passwordKey];
let confirmPassword = group.controls[confirmPasswordKey];
if (password.value !== confirmPassword.value) {
return {
mismatchedPasswords: true
};
}
}
}
如何在matchingPasswords
内传递当前表单?我尝试使用this
:
'passwordNewConfirmation')(this)
答案 0 :(得分:1)
ValidatorFn函数接受当前控件作为参数。您可以使用它来访问表单组。
export interface ValidatorFn {
(c: AbstractControl): ValidationErrors | null;
}
你的功能如下:
export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
return (control: AbstractControl): {
[key: string]: any
} => {
if(!control.parent){
return null;
}
let group = control.parent;
let password = group.controls[passwordKey];
let confirmPassword = group.controls[confirmPasswordKey];
if (password.value !== confirmPassword.value) {
return {
mismatchedPasswords: true
};
}
}
}
注册时,this
不需要:
this.changePasswordForm = this.formBuilder.group({
'passwordNew': ['', [ValidationService.passwordValidator, matchingPasswords('passwordNew', 'passwordNewConfirmation')]]
});