4

Duplicate :

Validate email address in JavaScript?

I want to validate emailid using JavaScript. I am using following code:

var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/ ;
var emailid=document.getElementById("<%=txtEmail.ClientID %>").value; 
var matchArray = emailid.match(emailPat);
if (txtemail.value!="")
{  
  if (matchArray == null)
  {
        alert("Your email address seems to be incorrect. \n Please type the proper email address and try again.") 
        return false
  }
}

This code is working for emails like, abc@xyz.com

But when i enter valid mailid like ab.cd@xyz.com or abc@xy-z.com, it is showing alert. What changes should I do in my coding, so it will not show alert for valid mail ids like above? Can anyone give me suggestions?

Community
  • 1
  • 1
Devashri B.
  • 2,593
  • 8
  • 25
  • 39

3 Answers3

3

Nice info with many examples:

http://www.regular-expressions.info/email.html

btw: + is valid character, I hate validators where I can't enter myemail+somenote@gmail.com (because gmail supports this)

DiGi
  • 2,528
  • 18
  • 26
3

http://regexlib.com/Search.aspx?k=&c=1&m=3&ps=50

Use whichever suits you best.

Cerebrus
  • 25,615
  • 8
  • 56
  • 70
2

I'd try changing your regular expression to this:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])
SquidScareMe
  • 3,108
  • 2
  • 24
  • 37