【发布时间】:2021-10-31 13:57:24
【问题描述】:
组件代码-
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 仍然无效,导致 整个表单 仍然无效。
为什么会发生这种情况以及如何解决?有人知道吗?
【问题讨论】:
-
请出示你的
ConfirmedValidator函数。 -
@JsNgian 我已经编辑了这个问题。但是,让我告诉你,ConfirmedValidator工作正常,没有任何问题即使在验证之后仍然无效。
-
matchCurrentPassword在这里做什么。您将密码与 ({ return x.isExecute ? { matches: true } : { matches: false }; }) 匹配什么? -
@JsNgian 场景是,如果任何用户想要更改他的密码,他必须输入他当前的密码,我将 传递给后端 & 与该用户的现有(当前)密码匹配。如果密码不匹配,则会显示错误消息。
标签: angular validation angular-reactive-forms mat-input mat-error