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

时间:2016-11-27 18:29:59

标签: forms angular custom-validators

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

这是我的Validator类:

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};
            }
       }
    }
}

我的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>

我的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'];
    }

最后我得到的例外:

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

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

1 个答案:

答案 0 :(得分:3)

由于验证器本身看起来很好,因此错误看起来很像select [column_names] from ( select e.*, t.*, ntile(5) over (order by state) as nt from ..... etc ) where nt = 1; select *,因为它是原始的。将control.value功能更新为以下内容:

undefined

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