如何正确地将异步验证添加到反应式表单中



在angular 13应用程序中,按照官方指南,我正在尝试实现异步验证

这里实现

检查电流密码.validator.ts

@Injectable({ providedIn: 'root' })
export class CheckCurrentPasswordValidator implements AsyncValidator {
constructor(private userService: UserService) {}
validate(
control: AbstractControl
): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return this.userService.verifyMatchWithCurrentPassword(control.value).pipe(
map((value) => (value ? null : { passwordMatch: true })),
catchError(() => of(null))
);
}
}

user.service.ts

@Injectable({
providedIn: 'root',
})
export class UserService {
constructor() {}
verifyMatchWithCurrentPassword(password: string): Observable<boolean> {
return of(password === 'password').pipe(delay(5000));
}
}

在文档中,没有明确说明如何将新的异步验证添加到表单中,所以我正在尝试以下

editPasswordForm: FormGroup = this.formBuilder.group(
{
currentPassword: [
'',
[
Validators.required,
this.checkCurrentPasswordValidator.validate(), // <-- async validation
],
],
newPassword: ['', Validators.required],
repeatNewPassword: ['', Validators.required],
},
{ validators: newPasswordMatchValidator }
);

在验证中,我得到以下错误消息

TS2554:应为1个参数,但得到了0。检查当前密码.validator.ts(15,5(:"control"的参数未提供

你能告诉我如何正确地将异步验证添加到反应表单中吗?

提前感谢

更新1

为了完成我的职责,我采用了另一种方式来添加异步验证器。后的所有信用

user.service.ts中,我添加了下一个方法

passwordValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return this.verifyMatchWithCurrentPassword(control.value).pipe(
map((value) => (value ? null : { passwordMatch: true }))
);
};
}

为了将异步验证器添加到表单中,我添加了这个

editPasswordForm: FormGroup = this.formBuilder.group(
{
currentPassword: [
'',
{
validators: [Validators.required],
asyncValidators: [this.userService.passwordValidator()],
updateOn: 'blur',
},
],
newPassword: ['', Validators.required],
repeatNewPassword: ['', Validators.required],
},
{ validators: newPasswordMatchValidator }
);

更新此:

editPasswordForm: FormGroup = this.formBuilder.group(
{
currentPassword: [
'',
[
Validators.required,
this.checkCurrentPasswordValidator.validate(), // <-- async validation
],
],
newPassword: ['', Validators.required],
repeatNewPassword: ['', Validators.required],
},
{ validators: newPasswordMatchValidator }
);

editPasswordForm: FormGroup = this.formBuilder.group(
{
currentPassword: [
'',
[Validators.required],
this.checkCurrentPasswordValidator.validate(),
],
newPassword: ['', Validators.required],
repeatNewPassword: ['', Validators.required],
},
{ validators: newPasswordMatchValidator }
);

最新更新