【问题标题】:mat-input still remains invalid after successful validation - Angular 12成功验证后,mat-input 仍然无效 - Angular 12
【发布时间】: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


【解决方案1】:

根据Defining custom validators

该函数采用 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>

Sample Solution on StackBlitz

【讨论】:

  • 谢谢。我这里有几个问题 { return x.isExecute ? null : { matches: false } } 在这里,返回的顺序 null 和 {matches: false } 重要吗?此外,Observable 这里应该将返回序列结构序列匹配吗?最后,为什么 Observable & Observable 都有效?
  • 1.这取决于您的逻辑,确保返回 null 以获取验证成功案例。 2.这更像是开发者的意见。在我看来,只要返回值与函数的返回类型匹配就可以了。 3.我更正了我的答案,应该是Observable&lt;ValidationErrors | null&gt;
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2014-11-13
  • 2017-10-06
  • 1970-01-01
  • 2018-10-02
  • 2019-02-17
相关资源
最近更新 更多