2017-05-26 82 views
-2

我在angular2中有一個電子郵件組件,我必須在下面進行驗證。Angular2電子郵件驗證無法正常工作

1)The email has a localpart on the left of an @, the domain on the right. Neither the localpart nor the domain may be empty 
2)Domain part can have any alphanumeric values 
3)Local part have any any alphanumerics and special characters Dot, underscore, hyphen. 
4)Domain part can have min 2 and max 4 characters affter the dot. 
5)No two consecutive dots are allowed in local part. 
6)Only special characters allowed are @,_,- and Dot 

在我的模板 -

<div class="controls"> 
      <md-input maxlength="60" placeholder="Customer Email" name="contactEmail" [(ngModel)]="emailProposal.customerEmail" #contactEmail="ngModel" id="contactEmail" (focus)="v_email=true;" (focusout)="v_email=false;"pattern="[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,6}$" 
       required></md-input> 
      <div *ngIf="!v_email && contactEmail.errors && (contactEmail.dirty || contactEmail.touched || sendEmailClicked)"> 
       <span class="validation-error-inline" *ngIf="!v_email && contactEmail.errors.required">{{errorMessages.contactEmailRequired}}</span> 
       <span class="validation-error-inline" *ngIf="!v_email && contactEmail.errors.pattern && (emailProposal?.customerEmail?.indexOf('...')==-1)">{{errorMessages.enterValidEmail}}</span> 
      </div> 
     </div> 

在我.ts-

@Input() emailSent: { customerEmail: string, confirmCustomerEmail: string, bindData: any }; 
@Output() onEmailQuote = new EventEmitter(); 


private errorMessages: { [key: string]: string } = { 
     contactEmailRequired: "This field is required.",    
     enterValidEmail: "Enter valid Customer email address.",   
    } 

validateEmail(email) { 
    var re = /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i; // regEx to check valid email 
    return re.test(email.customerEmail);   
    } 



private sendEmail() {  
     if (this.validateEmail(this.emailProposal) && this.hasMismatch() === false) { //allow the service call only when emails are valid    
      this.onEmailQuote.emit(this.emailSent); 
     } 

我正則表達式以上不符合6分above.Can有人提到幫我使用符合上述6個驗證規則的正確regEx。我僅在用戶列出fi時顯示錯誤消息或嘗試點擊發送按鈕與無效的電子郵件。電子郵件應發送只有當輸入有效的電子郵件。任何幫助,非常感謝。

+0

你的正則表達式有什麼問題?你能否提供有效/無效輸入樣本(爲了測試正則表達式)? – Mistalis

+0

valid-m @ m.com,m @ m.comy,invalid-m @ m.com%,m#m @ f.com7 –

回答

0

角有電子郵件驗證內置https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6https://github.com/angular/angular/pull/13709

只需添加電子郵件標籤。例如,

<form #f="ngForm"> 
    <input type="email" ngModel name="email" required email> 
    <button [disabled]="!f.valid">Submit</button> 
    <p>Form State: {{f.valid?'VALID':'INVALID'}}</p> 
    </form> 
+0

這隻適用於表單組的權利?在我的情況下,現有的代碼不使用表單組。 –

+0

不,它會使用模板驅動的表單也是它的一個驗證器,使用最新的角度版本雖然 –

+0

好吧,讓我試試吧。 –