我知道這個問題已經在許多其他帖子中提出過,但是在所有提出的解決方案中,我找不到一個可以為我解決問題的解決方案。
我正在嘗試創建一個驗證器來檢查輸入的確認密碼是否與密碼相同。
這是我的構建表單代碼:
this.form = new FormGroup({
name: new FormControl('', [Validators.required]),
surname : new FormControl('', [Validators.required]),
username: new FormControl('', [Validators.required, Validators.email]),
tempUsername: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]),
passwordTemp: new FormControl('', [Validators.required]),
}, { validator: this.matchingPasswords }
);
}
這是我的驗證器方法:
public matchingPasswords(c: AbstractControl): ValidationErrors | null {
const password = c.get(['passwords']);
const confirmPassword = c.get(['passwordTemp']);
if (password.value !== confirmPassword.value) {
return { mismatchedPasswords: true };
}
return null;
}
在構建表單的第 8 行中,我收到以下錯誤:
TS2345:'{驗證器型別的引數:(c:AbstractControl)=> ValidationErrors; }' 不可分配給型別為 'ValidatorFn | 的引數 驗證器Fn[] | 抽象控制選項'。物件字面量只能指定已知屬性,而 'validator' 型別中不存在 'ValidatorFn | 驗證器Fn[] | 抽象控制選項'。
有任何想法嗎?
uj5u.com熱心網友回復:
validators你不應該使用validator:
this.form = new FormGroup({
// fields
}, { validators: this.matchingPasswords });
也許將其移至matchingPasswords匯出的實用程式函式也更好,但這只是個人代碼偏好。
其他作業符號是:
this.form = new FormGroup({
// fields
}, this.matchingPasswords);
this.form = new FormGroup({
// fields
}, [this.matchingPasswords]);
uj5u.com熱心網友回復:
使用驗證器而不是驗證器
{ validators: this.matchingPasswords }
和這個
public matchingPasswords: ValidatorFn = (c: AbstractControl): ValidationErrors | null => {
const password = c.get('passwords');
const confirmPassword = c.get('passwordTemp');
if (password && confirmPassword && password.value !== confirmPassword.value) {
return { mismatchedPasswords: true };
}
return null;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433920.html
標籤:javascript 有角度的 验证 自定义验证器
上一篇:主鍵陣列中鍵的順序是否重要?
下一篇:如何從角度的過濾器中訪問值
