我有一个带有4个输入字段的表格,其中2个用于电子邮件,2个用于密码。我想检查电子邮件和密码是否匹配。我正在表单组中使用验证器。
accountInformation: FormGroup;
constructor(private fb: FormBuilder) {
this.accountInformation = this.fb.group({
emailAddress: [null, Validators.compose([Validators.required, Validators.email])],
emailAddressConfirmed: [null, Validators.compose([Validators.required, Validators.email])],
password: [null, Validators.compose([Validators.required, Validators.minLength(6)])],
passwordConfirmed: [null, Validators.compose([Validators.required, Validators.minLength(6)])],
}, {validator: this.matchValidator});
}
matchValidator(form: FormGroup) {
const passwordInput = form['value'];
if (passwordInput.password === passwordInput.passwordConfirmed) {
// These ones gives me errors in console
this.removeError(this.accountInformation.get('password'), 'mismatch');
// this.removeError(this.accountInformation.controls, 'mismatch');
// If I do these...
// form.controls['password'].setErrors(null);
// form.controls['passwordConfirmed'].setErrors(null);
// This will remove all errors of all types
} else {
form.controls['password'].setErrors({'mismatch': true});
form.controls['passwordConfirmed'].setErrors({'mismatch': true});
}
}
removeError(control: AbstractControl, error: string) {
const err = control.errors; // get control errors
if (err) {
delete err[error]; // delete your own error
if (!Object.keys(err).length) { // if no errors left
control.setErrors(null); // set control errors to null making it VALID
} else {
control.setErrors(err); // controls got other errors so set them back
}
}
}
我在控制台中收到此错误:
Error: Uncaught (in promise): TypeError: Cannot read property 'get' of
undefined TypeError: Cannot read property 'get' of undefined
at FormGroup.push../src/app/components/register/register.component.ts.RegisterComponent.matchValidator
[as validator]
在这些字段中,我也有required
和minlength
,如果我愿意setErrors(null)
,也不想丢掉它们。另外,我也不知道如何检查电子邮件。也许我使代码过于复杂。
答案 0 :(得分:2)
仅当errors数组中没有其他错误时,才需要将error设置为null。例如,您可以检查长度。
答案 1 :(得分:0)
您可以在获取表单控件的值之前尝试进行null检查;
matchValidator(control: AbstractControl) {
const password: string = control.get('password').value; // get password from our password form control
const passwordConfirmed: string = control.get('passwordConfirmed').value; // get password from our passwordConfirmed form control
// compare is the password math
if (password !== passwordConfirmed) {
// if they don't match, set an error in our passwordConfirmed form control
control.get('passwordConfirmed').setErrors({ mismatch: true });
}
}