2016-11-27 5 views
0

입력이 유효한 전자 메일 형식인지 확인하기 위해 사용자 지정 유효성 검사기를 만들고 있습니다.Angular2 사용자 지정 유효성 검사기를 만드는 방법

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은 그 다음과 같습니다 :

이 내 Validator 클래스입니다

<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 

나는 나의 match가 정의되지 않은 이유와 어떻게 custom validator를 구현하는 것이 가장 적절한가?

답변

2

유효성 검사기 자체가 정상적으로 보이기 때문에 은 원래 그대로이므로 undefined과 비슷합니다. 다음에 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

또한 폼에 컨트롤을 바인딩하는 것에 대한 질문이 있습니다. 'form' (이 경우'div' 엘리먼트)에'[formGroup] = "signupForm"으로'formControlName = "email"이되어서는 안됩니까? 그러나 유효성 검사기와 관련하여 간단한 추가 검사는 수행하지 않습니다 : 'if (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