2016-11-27 74 views
0

我正在製作一個自定義驗證器來檢查輸入是否爲有效的電子郵件格式。如何在Angular2中製作自定義驗證器

這是我的Validator類:

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

export class EmailValidator { 

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

      if (!control.value.match(/^\[email protected][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 

我的問題是,爲什麼我的比賽是不確定的,怎麼會是最合適的實現自定義的驗證?

回答

2

由於驗證器本身看起來很好,所以錯誤看起來很像您的control.valueundefined,因爲它是原始的。更新emailValidator功能如下:

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

     if (control.value && !control.value.match(/^\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) { 
      return {invalidChars: true}; 
     } 
    } 

所以它會嘗試用正則表達式的測試值只有在情況下,有一個提供一個。

+0

control.value未定義。我在加載頁面時遇到了這個異常。 – GaborH

+0

另外,我有一個關於綁定控件到表單的問題。它不應該是'formControlName ='email'','formGroup] =「signupForm」'在一個'form'上(在這個例子中是'div'元素)? 而對於驗證,不會簡單的額外的檢查:!?。 '如果(control.value && control.value.match(/^\ w + @ [A-ZA-Z _] + \ [A-ZA-Z ] {2,3} $ /)){'是一個解決方案? –

+0

這就是問題所在,我沒有想到。我添加了(control.value &&!control.value.match(/^\ w + @ [a-zA-Z _] +?\。[a-zA-Z] {2,3} $ /)),首先如果它有價值,而且只要該領域沒有變化,那麼就沒有價值。如果你用解決方案編輯你的答案,我會接受它作爲答案。 – GaborH