2017-02-28 52 views
0

所以這裏是我的麻煩,我驗證電子郵件,我想要有點寬容(取決於電子郵件應該是絕對完美或不),這樣做我使用帶有參數withsuspicious一個自定義的驗證(即會觸發可疑電子郵件的除外)所以這裏是我的代碼:角度,在驗證模型中傳遞參數

組件:

FormEmailAddress : FormGroup; 
constructor(private fb: FormBuilder) { } 
ngOnInit(){ 
this.FormEmailAddress = this.fb.group({ 
     emailAddress: ['', Email.validateEmail] 
    }); 
} 

驗證:

static validateEmail(control, withsuspicious) { 
     if (Validators.required(control)!== undefined && Validators.required(control)!== null) return null; 
     return Email.checkValidity(control.value, withsuspicious)? null : { pattern: {invalid: true}} 

    } 

Email.checkValidity僅僅是通過返回如果真正好的驗證電子郵件的功能,否則爲false(與正則表達式等)

查看

<form [formGroup]="FormEmailAddress" novalidate> 
    <h4>Email Model Driven</h4> 
    <input type="text" formControlName="emailAddress"/> 
    <p>Email : {{FormEmailAddress.get('emailAddress').value}}</p> 
    <p *ngIf="!FormEmailAddress.valid"> Wrong Email </p> 
</form> 

所以我想找到一種方法來傳遞,以及我的「emailAddr」參數與我的驗證器可疑可以幫助我嗎?由於

回答

0

終於找到了如何做到這一點,並沒有改變視圖或驗證什麼,中庸之道這樣做的組件:

this.FormEmailAddress = this.fb.group({ 
      emailAddress: [''], 
      withsuspicious: [true] 
     }, {validator : this.validateEmail('emailAddress', 'withsuspicious')}); 
validateEmail(emailAddressKey, withsuspiciousKey){ 
     return(group : FormGroup) => { 
      let emailInput = group.controls[emailAddressKey] 
      let withsuspiciousInput : boolean = group.controls[withsuspiciousKey].value 

      return Email.validateEmail(emailInput, withsuspiciousInput) 
     } 
    }