我必須驗證我有兩個密碼匹配。我找到了這個解決方案:Angular 11 How to validate confirmPassword is same as password using Reactive forms這似乎有效。
但是:我正在使用一個組件庫,它會在組件出錯時自動設定組件樣式。這里的問題是我的確認密碼不會變紅,因為錯誤附加到整個表單而不是特定欄位。
我怎樣才能做到這一點:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div >
<kendo-floatinglabel text="Password" >
<input kendoTextBox formControlName="password" type="password" />
</kendo-floatinglabel>
<kendo-floatinglabel text="Repeat password" >
<input
kendoTextBox
formControlName="confirmPassword"
type="password"
/>
</kendo-floatinglabel>
</div>
</form>
有了這個組件
loginForm = this.fb.group(
{
password: ['', Validators.required],
confirmPassword: ['', Validators.required],
},
{ validators: this.confirmPasswordMatching }
);
passwordMatchingValidatior(
control: AbstractControl
): ValidationErrors | null {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
return password?.value === confirmPassword?.value
? null
: { notmatched: true };
}
但是將錯誤附加到該欄位?
uj5u.com熱心網友回復:
您可以嘗試像這樣setErrors在confirmPassword控制元件上:
passwordMatchingValidatior(
control: AbstractControl
): ValidationErrors | null {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
const error = { notmatched: true };
const isValid = password?.value === confirmPassword?.value;
if (!isValid) {
confirmPassword?.setErrors(error);
}
return isValid ? null : error;
}
uj5u.com熱心網友回復:
我在這里看到兩個選項,
訪問輸入元素并根據有效性在輸入上添加/洗掉
ng-invalid和類。ng-valid收聽表單控制元件并手動設定錯誤/洗掉錯誤。
這是一個監聽表單控制元件更改并用于setErrors設定/洗掉錯誤的示例。使用alive設定為falsein的布爾變數OnDestroy。
get confirmPassword() {
return this.loginForm.get('confirmPassword') as FormControl;
}
ngOnInit() {
combineLatest([
this.loginForm.get('password').valueChanges.pipe(startWith('')),
this.loginForm.get('confirmPassword').valueChanges.pipe(startWith('')),
])
.pipe(takeWhile(() => this.alive))
.subscribe((values: [string, string]) => {
if (!values[1]) {
this.confirmPassword.setErrors({ required: true });
return;
} else if (values[0] !== values[1]) {
this.confirmPassword.setErrors({ notmatched: true });
return;
}
this.confirmPassword.setErrors(null);
});
}
所以這個選項根本沒有自定義驗證器。
uj5u.com熱心網友回復:
您可以[showErrorIcon]="!loginForm.valid"在“確認密碼輸入”中使用。查看檔案
<kendo-textbox id="confirm"
[style.width.px]="350"
formControlName="confirmPassword"
[showErrorIcon]="!form.valid && form.get('confirmPassword').touched"
[clearButton]="true"
>
</kendo-textbox>
要“帶邊框的紅色”,您可以使用 .css。如果您的確認密碼有 id="confirm"
form.ng-invalid #confirm.ng-touched
{
border-color:red
}
form.ng-invalid #confirm.ng-touched .k-icon
{
color:red
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/464268.html
