Validate e-mail with Angularjs

Asked

Viewed 2,749 times

1

I have the following field for e-mail:

<input type="email" class="form-control" id="email" name="email" ng-model="fields.email" required="true" />

In the div where the field is, I have the following validation:

ng-class="{ 'has-error': userForm.email.$error.email }"

It turns out that if you type "abc@abc" is given as valid, but as we can see is wrong.

I have tried using regular expression but without success. How to validate emails correctly in Angularjs?

2 answers

2


Utilize ngPattern to change the Angular default behavior:

<input type="email" <!-- ... --> ng-model="fields.email" ng-pattern="/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/" />

Check out the Angular documentation for more information:

Angularjs: input[email]

  • I just made a modification, as the business rule is all within the . js, created a variable within the scope and added the regular expression there, worked perfectly with this.

2

Actually the abc@abc email can be valid in the same way as email@localhost.

It is unusual, but is valid technologically speaking, could answer some address.

You can check in: http://en.wikipedia.org/wiki/Email_address#Examples

I don’t even know how this will behave with new custom domains like . google or . globe, they already exist and maybe can use emails this way, but then I’m not sure.

  • True, but they are still unusual and as you said, no one knows yet how they will behave with the new domains.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.