组件代码-
ngOnInit(): void {
this.form = this.fb.group({
currentPassword: ['', [Validators.required], [this.matchCurrentPassword]],
newPassword: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(12)]],
confirmPassword: ['', [Validators.required]]
}
, { validator: this.ConfirmedValidator('newPassword', 'confirmPassword') }
)
}
matchCurrentPassword = (
control: AbstractControl
): Observable<ValidationErrors | ValidationErrors> => {
return this.userService.matchCurrentPassword(localStorage.getItem("userId"), control.value)
.pipe
(tap(x => { console.log("response:", x) }),
(map((x: any) => { return x.isExecute ? { matches: true } : { matches: false }; }))
)
}
ConfirmedValidator(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.confirmedValidator) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ confirmedValidator: true });
} else {
matchingControl.setErrors(null);
}
}
}
Html代码——
<mat-form-field appearance="outline" fxFlex="1 1 calc(100% - 10px)"fxFlex.lt-md="1 1 calc(100% - 10px)" fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color">
<mat-label class="label-padding">Enter Current Password</mat-label>
<input type="password" class="label-padding" type="text" style="-webkit-text-security: disc;"matInput placeholder="Current Password" formControlName="currentPassword" />
<mat-error *ngIf="currentPassword.errors?.required && currentPassword.touched">Enter current password</mat-error>
<mat-error *ngIf="currentPassword.errors?.matches==false">Doesn't match</mat-error>
</mat-form-field>
验证是否匹配当前密码工作完美&根据条件显示错误信息。但是它的输入字段仍然无效在那之后。
我还尝试验证其余的输入字段。但是currentPassword仍然无效&导致整个表单剩余的无效的.
为什么会发生这种情况&如何解决这个问题?有人知道吗?
根据定义自定义验证器,
该函数接受一个Angular控件对象,如果控件值有效,则返回null或一个验证错误对象。
如果验证有效,则需要为matchCurrentPassword
函数返回null
.
解决方案验证失败时,返回matchCurrentPassword
函数中的{ matches: true }
。
.component.ts
matchCurrentPassword = (
control: AbstractControl
): Observable<ValidationErrors | null> => {
let userId = localStorage.getItem('userId');
return this.userService.matchCurrentPassword(userId, control.value).pipe(
tap(x => {
console.log('response:', x);
}),
map((x: any) => {
return x.isExecute ? null : { matches: true };
})
);
};
.component.html
<mat-error *ngIf="currentPassword.errors?.matches">Doesn't match</mat-error>
StackBlitz的样例解决方案