DiP*_*Pix 3 typescript angular angular-reactive-forms
我有与这里类似的问题:
我已经阅读了问题,但问题仍然出现在 linter 中:
不推荐使用组:此 API 不是类型安全的,可能会导致 Closure Compiler 重命名问题。使用
FormBuilder#group重载 withAbstractControlOptions代替。请注意,AbstractControlOptions期望validators和asyncValidators将成为有效的验证器。如果您有自定义验证器,请确保它们的验证函数参数是AbstractControl而不是子类,例如FormGroup. 这些函数将使用类型的对象调用,AbstractControl并且不能自动向下转换为子类,因此 TypeScript 将此视为错误。例如,将(group: FormGroup) => ValidationErrors|null签名更改为(group: AbstractControl) => ValidationErrors|null。(弃用)
这是我的 formBuilder:
registerForm = this._fb.group({
firstname: ["", [Validators.required]],
lastname: ["", [Validators.required]],
email: ["", [Validators.required, Validators.email]],
password: ["", [PasswordValidator.strength]],
confirmPassword: ["", [Validators.required]]
}, {
validator: PasswordValidator.confirmed("password", "confirmPassword")
});
Run Code Online (Sandbox Code Playgroud)
还有我的验证器:
export class PasswordValidator {
static confirmed = (controlName: string, matchingControlName: string) => {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
return null;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true });
return ({ confirmedValidator: true });
} else {
matchingControl.setErrors(null);
return null;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?我正在返回正确的对象。:/
@OwenKelvin 部分正确。它必须是validators不是validator在formBuilder,尽管这只是一个验证,对不起欧文一次。
但第二个问题是在验证器中。该函数应AbstractControl改为接收FormGroup. 所以下面的代码是正确的:
export class PasswordValidator {
static confirmed = (controlName: string, matchingControlName: string) => {
return (control: AbstractControl): ValidationErrors | null => {
const input = control.get(controlName);
const matchingInput = control.get(matchingControlName);
if (input === null || matchingInput === null) {
return null;
}
if (matchingInput?.errors && !matchingInput.errors.confirmedValidator) {
return null;
}
if (input.value !== matchingInput.value) {
matchingInput.setErrors({ confirmedValidator: true });
return ({ confirmedValidator: true });
} else {
matchingInput.setErrors(null);
return null;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
你在哪里得到错误?我用你的代码做了一个 stackblitz,但我看不到它
顺便说一句,我不太喜欢使用 setError 将错误“放入”控件。
如果您不使用 mat-error,您可以简单地询问 form.errors。
如果你使用 mat-error 你可以
bind(this)并询问 this.registerForm.password,请参阅另一个 SO| 归档时间: |
|
| 查看次数: |
1595 次 |
| 最近记录: |