如何在Angular 7中显示自定义验证错误

时间:2019-02-07 19:27:07

标签: javascript angular

我想在表单的输入字段和消息Password is invalid周围以及用户输入的密码与设置的密码不匹配时显示红色边框。

当我输入与设置的密码不同的内容但未显示该消息时,我会看到红色边框,表明存在错误。花了几个小时检查我的代码后,我一直无法弄清楚问题出在哪里,所以请仔细查看我的代码并指出错误

password.validators.ts

import { AbstractControl, ValidationErrors } from "@angular/forms";

export class PasswordValidators {
    static matchOldPassword(
       control: AbstractControl
       ): Promise<ValidationErrors | null> {
       return new Promise((resolve, reject) => {
           setTimeout(() => {
           if (control.value !== "1234") resolve({ matchOldPassword: true });
           else resolve(null);
           }, 2000);
       });
   }
}

password-change.component.ts

import { PasswordValidators } from "./password.validator";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { Component } from "@angular/core";

@Component({
  selector: "password-change",
  templateUrl: "./password-change.component.html",
  styleUrls: ["./password-change.component.css"]
})
export class PasswordChangeComponent {
  form = new FormGroup({
    oldPassword: new FormControl(
    "",
    Validators.required,
    PasswordValidators.matchOldPassword
    )
  });
}

password-change.component.html

<form [formGroup]="form">
<div class="form-group">
<label for="oldPassword" class="font-weight-bold">Old Password</label>
<input
  formControlName="oldPassword"
  type="password"
  id="oldPassword"
  class="form-control"
/>
<div
  *ngIf="oldPassword.touched && oldPassword.pristine"
  class="text-danger"
>
  <div *ngIf="oldPassword.errors.required">Old password is required.</div>
  <div *ngIf="oldPassword.errors.matchOldPassword">
    Old password is not valid.
  </div>
</div>
</div>
</form>

1 个答案:

答案 0 :(得分:1)

从包裹oldPassword.pristine中删除div。修改字段后,您的if变得虚假,因为它不再是原始数据,因此不会显示整个div。否则,您的代码看起来不错!因此,您的包装div应该如下所示:

<div *ngIf="oldPassword.touched">

StackBlitz