嘗試使用 Angular 創建自定義驗證器時遇到問題。事實上,對于我的注冊頁面,我創建了一個表單并檢查密碼和確認密碼是否匹配,我想創建一個自定義驗證器。
但是我遇到了下一個問題(見圖),即使是我在 Internet 上發現的所有類似請求,也沒有解決我的問題。
問題是:

import { FormControl, FormGroup, Validators } from '@angular/forms';
import { USER_ATTRIBUTS } from 'src/app/globalVariable';
import { CustomValidators } from 'src/app/validators/custom-validators'
export class UserFormSignUp extends FormGroup{
constructor(){
super({firstName: new FormControl('',[
Validators.required]),
lastName: new FormControl('',[
Validators.required]),
birthdate: new FormControl('',
Validators.required),
displayName: new FormControl('',[
Validators.required,]),
email: new FormControl('',[
Validators.required,
Validators.email]),
password: new FormControl('',[
Validators.required]),
confirmationPassword: new FormControl('',[
Validators.required])},
{
validator: CustomValidators.passwordMatchValidator
});
}
get firstName() : FormControl{
return this.get('firstName') as FormControl;
}
get lastName() : FormControl{
return this.get('lastName') as FormControl;
}
get birthdate() : FormControl{
return this.get('birthdate') as FormControl;
}
get displayName() : FormControl{
return this.get('displayName') as FormControl;
}
get email() : FormControl{
return this.get('email') as FormControl;
}
get password() : FormControl{
return this.get('password') as FormControl;
}
get confirmationPassword() : FormControl{
return this.get('confirmationPassword') as FormControl;
}
}
和自定義驗證器.ts:
import { ValidationErrors, ValidatorFn, AbstractControl } from '@angular/forms';
checkPasswords: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
let pass = group.get('password')?.value;
let confirmPass = group.get('confirmPassword')?.value
return pass === confirmPass ? null : { notSame: true }
}
}
如果你有任何想法......我會很感激。
uj5u.com熱心網友回復:
通過擴展FormGroup,并要求super與{ validator: CustomValidators.passwordMatchValidator }你不符合實際的建構式簽名FormGroup這是應該采取一個普通ValidatorFn的第二個引數,像你這樣沒有嵌入的物件。
像這樣嘗試:
export class UserFormSignUp extends FormGroup {
constructor() {
super(
{
firstName: new FormControl("", [Validators.required]),
lastName: new FormControl("", [Validators.required]),
birthdate: new FormControl("", Validators.required),
displayName: new FormControl("", [Validators.required]),
email: new FormControl("", [Validators.required, Validators.email]),
password: new FormControl("", [Validators.required]),
confirmationPassword: new FormControl("", [Validators.required]),
},
CustomValidators.passwordMatchValidator
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371535.html
標籤:javascript 有角的 打字稿 形式 自定义验证器
