【问题标题】:How to add custom validator to reactive forms in Angular5如何在 Angular5 中向反应表单添加自定义验证器
【发布时间】:2018-03-17 10:31:36
【问题描述】:

我有以下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>

【问题讨论】:

    标签: angular5 custom-validators


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-16
      • 2019-07-09
      • 1970-01-01
      • 2014-04-05
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多