当我试图创建一个带有角的自定义验证器时,我面临着一个问题。实际上,在我的注册页面中,我创建了一个表单并检查密码et confirmPassword是否匹配,我想创建一个自定义验证器。
但是我面临着下一个问题(见图),即使是我在互联网上发现的所有相似的请求,它也没有解决我的问题。
问题是:

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;
}}
以及自定义验证器:
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 }
}}
如果你有任何想法..。我会接受的。
发布于 2021-11-29 22:30:44
通过扩展FormGroup并使用{ validator: CustomValidators.passwordMatchValidator }调用super,您将不遵守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://stackoverflow.com/questions/70162065
复制相似问题