我正在编写用于密码的角单元测试用例并确认密码验证。
validation.ts文件
export function matchPasswords(
passwordFieldName: string,
confirmPasswordFieldName: string
): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const password = control.get(passwordFieldName).value;
const confirmPassword = control.get(confirmPasswordFieldName).value;
if (password !== confirmPassword) {
control
.get(confirmPasswordFieldName)
.setErrors({ passwordsDoNotMatch: true });
return { passwordsDoNotMatch: true };
} else {
return null;
}
};
}
validation.spec.ts代码
it('should match both password fields and return null if both matches', () => {
var passwordField1: string = "Admins@123";
var confirmPasswordField1: string = "Admins@123";
const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
expect(
validate({value:{
'passwordFieldName':passwordField1,
'confirmPasswordFieldName':confirmPasswordField1}} as AbstractControl)
.toEqual(null));
});
在一行control.get(passwordFieldName).value,我得到了错误control.get不是一个函数。
您将需要将验证器应用于FormGroup,这将使您可以访问所需的FormControl。目前,您正在传递AbstractControl / FormControl,它本质上是一个表单字段。
函数可能看起来像这样。
export function matchPasswords: ValidatorFn = (fg: FormGroup) => {
const password = fg.get('passwordFieldName').value;
const confirmPassword = fg.get('confirmPasswordFieldName').value;
return password === confirmPassword
? null
: { passwordsDoNotMatch: true };
};