1

I want to validate an email id in angular 2 Now i am using

( /^(([^<>()\[\]\\.,;:\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,}))$/) 

But if we leave the field empty, it will remain invalid.

so can you suggest me an better option for validating email

Cœur
  • 34,719
  • 24
  • 185
  • 251
sainu
  • 2,666
  • 2
  • 21
  • 40

2 Answers2

1

Add |(^$) at the end of your reg exp to accept empty string:

( /^(([^<>()\[\]\\.,;:\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,}))$|(^$)/)
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
0

Try this :

(/^([0-9a-zA-Z]([_\\.]*[0-9a-zA-Z]+)*)@([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/)
Arun Tyagi
  • 2,046
  • 5
  • 22
  • 35
  • 1
    Why are you limiting TLD to 9 characters? Have a look at http://www.iana.org/domains/root/db And why haven't you kept the special characters present in OP? – Toto Jun 09 '16 at 10:04