我有password
和confirm_password
字段的注册表单。我有自定义验证来检查这些密码是否相同。问题是:当我在password
字段中输入'qwerty123'而在qwerty123
字段中输入password_confirm
时,一切都很好。但是,如果我然后在4
字段中添加一些字符confirm_password
,然后将相同的字符4
添加到password
字段,则表单将无效(属性valid
是false
),我无法用它做任何事情。
我在这里查看了类似的解决方案,但那些有用的东西对我没用。
我的组成部分:
public userNameInput: FormControl = new FormControl('', [
Validators.minLength(this.limits['username'][0]),
Validators.maxLength(this.limits['username'][1])
]);
public emailInput: FormControl = new FormControl('', [
Validators.required,
RegisterFormComponent.checkEmail
]);
public passwordInput: FormControl = new FormControl('', [
Validators.required,
Validators.minLength(this.limits['password'][0]),
Validators.maxLength(this.limits['password'][1]),
RegisterFormComponent.checkPasswordsMatching
]);
public confirmPasswordInput: FormControl = new FormControl('', [
Validators.required,
RegisterFormComponent.checkPasswordsMatching
]);
public registrationForm: FormGroup = this.formBuilder.group({
userName: this.userNameInput,
email: this.emailInput,
password: this.passwordInput,
confirmPassword: this.confirmPasswordInput
});
private static checkPasswordsMatching(input: FormControl): null | { [ key: string ]: boolean } {
if (!input.root || !input.root.get('password')) {
return null;
}
return (
(
input.root.get('password').value === '' ||
input.root.get('confirmPassword').value === ''
)
||
input.root.get('password').value ===
input.root.get('confirmPassword').value
)
? null
: { mismatched: true };
}
我的HTML来自模板:
<input
type="text"
name="username"
id="username"
[formControl]="userNameInput"
[class.error]="
userNameInput.hasError('minlength') ||
userNameInput.hasError('maxlength')
"
>
<input
id="email"
type="text"
name="email"
[formControl]="emailInput"
[class.error]="
!emailInput.pristine &&
emailInput.hasError('invalid')
"
>
<input
type="password"
name="password"
id="password"
[formControl]="passwordInput"
[class.error]="
passwordInput.hasError('minlength') ||
passwordInput.hasError('maxlength') ||
confirmPasswordInput.hasError('mismatched')
"
>
<input
type="password"
name="password_confirm"
id="password_confirm"
[formControl]="confirmPasswordInput"
[class.error]="
passwordInput.hasError('mismatched') ||
confirmPasswordInput.hasError('mismatched')
"
>
<button
[disabled]="!registrationForm.valid"
>Confirm</button>
答案 0 :(得分:1)
这是因为angular不会在其他输入上重新运行验证器,只是在当前正在输入的用户上。您可以使用updateValueAndValidity
在另一个输入上重新运行验证器。