[英]Setting error on form control field based on the value of another field
我有一個編輯用戶對話框,允許用戶在其中編輯用戶屬性。 要編輯密碼,我需要用戶輸入新密碼並確認。 僅當密碼字段具有某些值時,確認密碼字段才應該是強制性的,因為用戶也可以編輯除密碼之外的其他值。 我正在嘗試通過自定義驗證器執行此操作,但無法這樣做。 請幫忙。 提前致謝。
這是我的表單組:
this.userForm = new FormGroup({
username: new FormControl(this.data.user.username, [Validators.required]),
firstName: new FormControl(this.data.user.firstName, [Validators.required]),
email: new FormControl(this.data.user.email, [Validators.required, Validators.email]),
password: new FormControl('', []),
passwordAgain: new FormControl('', [isEmpty('password') ]),
});
我的自定義驗證器:
export function isEmpty(matchingControlName: string): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (!control.parent) {
return null;
}
const dest = control.parent.controls[matchingControlName];
// // set error if validation fails
if (control.value==='' && dest.value!='') {
return { empty: true };
} else {
return null;
}
};
}
首先,您可以在自定義驗證器中添加另一個條件
if (control.value==='' && dest.value!='') {
return { empty: true };
} else {
return control.value!=dest.value?{notMatch:true}:null;
}
是的,自定義驗證器可以返回不同的錯誤 - 你檢查*ngIf="userForm.get('passwordAgain').errors?.empty"
和*ngIf="userForm.get('passwordAgain').errors?.notMatch"
但主要問題是 Angular 僅在您更改控件時檢查控件的驗證器。 為此,您可以采取兩種方法
1.- 在提交中,在發送值之前再次對控制密碼進行 updateValueAndValidity
submit(userForm:FormGroup){
//updateValue and validity the "passwordAgain"
userForm.get('passwordAgain').updateValueAndValidity();
//mark all controls as touched
userForm.markAllAsTouched()
if (userForm.valid)
{
.....your code...
}
}
2.-創建表單后訂閱密碼 valueChange 到 updateValueAndValidity paswwrodAgain
this.userForm.get('password').valueChanges.subscribe(_=>{
this.userForm.get('passwordAgain').updateValueAndValidity()
})
更新在看到 MikOne 的評論后,還有另一個選項是在 formGroup 上創建驗證器-這使得任何輸入中的任何更改都執行驗證器-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.