Angular2-email验证无法正常工作

时间:2017-05-26 09:13:45

标签: regex typescript angular2-template

我在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._%+-]+@[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 = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{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);
        }

我上面的regEx不符合上面提到的6点。可以帮助我使用符合上述6个验证规则的正确regEx。我只有当用户选中该字段或尝试点击发送按钮时才会显示错误消息无效的电子邮件。只有在输入有效的电子邮件时才会发送电子邮件。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Angular内置了https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://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>