如何在 Angular2 中制作自定义验证器

Gab*_*orH 1 forms custom-validators angular

我正在制作一个自定义验证器来检查输入是否是有效的电子邮件格式。

这是我的验证器类:

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

export class EmailValidator {

    static getEmailValidator() {
        return function emailValidator(control: FormControl): { [s: string]: boolean } {

            if (!control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
                return {invalidChars: true};
            }
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 HTML 看起来像这样:

<div class="form-group">

    <input  class="form-control"
            [(ngModel)]="model.email"
            type="text"
            id="name"
            placeholder="Enter your email"
            [formControl]="signupForm.controls['email']"

     >
     <div *ngIf="signupForm.controls['email'].errors?.required&& signupForm.controls['email'].touched"
          class="alert alert-danger">Email is required</div>
     <div *ngIf="signupForm.controls['email'].hasError('invalidChars') && signupForm.controls['email'].touched"
          class="alert alert-danger">Please give a valid email address</div>
Run Code Online (Sandbox Code Playgroud)

我的 HTML 组件:

export class SignupComponent  {


    signupForm: FormGroup;
    email: AbstractControl;

    model: any = {};
    response: any;


    constructor(fb: FormBuilder, private userService: UserService) {
        this.signupForm = fb.group({
            'email' : ['', Validators.compose([Validators.required, EmailValidator.getEmailValidator()])]

        });
        this.email = this.signupForm.controls['email'];
    }
Run Code Online (Sandbox Code Playgroud)

最后我得到的例外是:

Uncaught (in promise): Error: Error in ./SignupComponent class 
SignupComponent - inline template:31:4 caused by: Cannot read property 
'match' of undefined TypeError: Cannot read property 'match' of undefined at
 emailValidator
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我的匹配未定义,以及如何最适合实现自定义验证器?

Dan*_*ian 5

由于验证器本身看起来不错,因此错误看起来很像您的错误control.valueundefined因为它是原始的。将函数更新emailValidator为以下内容:

static getEmailValidator() { 
    return function emailValidator(control: FormControl): { [s: string]: boolean } {

        if (control.value && !control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
            return {invalidChars: true};
        }
    }
Run Code Online (Sandbox Code Playgroud)

因此,只有在提供了正则表达式的情况下,它才会尝试使用正则表达式来测试值。