-1

组件代码-

    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仍然无效,这会导致整个表单仍然无效

为什么会发生这种情况以及如何解决?有谁有想法吗?

4

1 回答 1

1

根据定义自定义验证器

该函数采用 Angular 控件对象,如果控件值有效则返回 null 或验证错误对象。

如果验证有效则需要返回nullmatchCurrentPassword函数。


解决方案

{ matches: true }并在matchCurrentPassword验证失败时返回函数。

.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 上的示例解决方案

于 2021-09-02T05:38:56.090 回答