我的註冊表格中有password
和confirm_password
字段。我有自定義驗證來檢查這些密碼是否相同。問題是:當我在password
字段中輸入'qwerty123'並且在password_confirm
字段中輸入qwerty123
時,一切正常。但是,如果我然後添加一些字符,例如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>
你是否檢查你得到哪個錯誤?可能是因爲'密碼'字段太長了?因爲你有驗證最大長度那裏,但不是'confirmPasswordInput' – Ludevik
不是,這是'錯配'的錯誤,它不是肯定的長度。 – WeekendMan