Angular2 email validation

2020-02-07 17:58发布

I am new in learning Angular2, and I want to make a validation form that verifies emails after a RegEx pattern.

My code looks something like this but I don't have any idea if I am doing it right, or what I did wrong, can somebody please help me a bit?

Thank you!

I fixed it. Thank you a lot everybody.

<div class="alert-email">
    <label for="contactemail">EMAIL: </label>
    <input type="email" id="contactemail" name="contactemail"
           required ng-pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
           [(ngModel)]="model.contactemail" #contactemail="ngModel"
           placeholder="Your email" /><br><br>
    <div *ngIf="contactemail.errors && (contactemail.dirty || contactemail.touched)" class="alert-email alert-danger-email"><br>
      <div [hidden]="!contactname.errors.required">
        Email is required
      </div>
      <div [hidden]="!contactname.errors">
        Please input a valid email.
      </div>
    </div>
  </div>

8条回答
乱世女痞
2楼-- · 2020-02-07 18:37

You can use this pattern for your email inputs:

^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$

ref

This pattern accepts "sample@domain" also in addition of "sample@domain.dom". Using this email pattern "sample@domain." is not acceptable and 1 letter domain tld is not allowed ("sample@domain.s" goes wrong).

查看更多
够拽才男人
3楼-- · 2020-02-07 18:39

This pattern worked for me which will accept alphanumeric characters and '.' special character.

^[\\w]+(?:\\.[\\w])*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$
查看更多
登录 后发表回答