如何在Angular5中为自动形式添加自定义验证器

时间:2018-03-17 10:31:36

标签: angular5 custom-validators

我有以下passwordvalidator我不知道如何附加到html中。我现在调用它的方式是 loginForm.controls.password.errors.passwordValidator 请参阅下面的实际代码。

import { FormControl } from "@angular/forms";

    export class PasswordValidator {

        static getPasswordValidator() {
            return function passwordValidator(control: FormControl): { [s: string]: boolean } {

                // Write code here..
                if (!control.value.match(/^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,})/)) {
                    return { invalidPassword: true };
                }

                return null;
            }
        }
    }

然后我就在 login.ts

中使用它
  ngOnInit() {
    this.loginForm = this.fb.group({
      username: ['', [Validators.required, Validators.email]],
      password: ['',
        Validators.compose([
          Validators.required,
          PasswordValidator.getPasswordValidator()
        ]
        )]
    });
  }

但无法找到如何将其添加到 login.html

中的formcontrol
<mat-form-field class="example-full-width">
    <input id="password" formControlName="password" matInput placeholder="Password">
  </mat-form-field>
  <br>
  <div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
    class="alert alert-danger">
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
      You must fill out your password
    </div>
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.passwordValidator && !loginForm.controls.password.errors.required">
      Invalid email password
    </div>

1 个答案:

答案 0 :(得分:1)

您应该检查密钥invalidPassword是否存在于该控件的错误中

<mat-form-field class="example-full-width">
    <input id="password" formControlName="password" matInput placeholder="Password">
</mat-form-field>
<br>
<div *ngIf="loginForm.controls.password.invalid && (loginForm.controls.password.dirty || loginForm.controls.password.touched)"
    class="alert alert-danger">
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.required">
    You must fill out your password
    </div>
    <div class="error mat-body-2" *ngIf="loginForm.controls.password.errors.invalidPassword && !loginForm.controls.password.errors.required">
    Invalid email password
    </div>