0

The below code is for validating email. I am getting false for inputs like,

mike@gmail.com

kid@gmail.com

stain@yahoo.com

Can someone point what mistake in the code?

   function validate(){
    fieldValue = document.getElementById("check").value;
    pattern = new RegExp(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/);       
    if(pattern.test(fieldValue)){
        alert("true");
    } else {
        alert("false");
    }       
}  

Thanks

Code
  • 219
  • 2
  • 11
  • 1
    Related reading: http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/ – DA. May 14 '14 at 03:15
  • I believe it is the casing – sebagomez May 14 '14 at 03:16
  • 1
    Don't reinvent wheel. http://stackoverflow.com/questions/19605773/html5-email-validation – Paul May 14 '14 at 03:18
  • 1
    related: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – jspurim May 14 '14 at 03:18
  • 1
    Why are you giving a RegExp literal as the argument to `new RegExp`? You can just do `pattern = /.../;`. Also, you should use local variables, not global variables. – Barmar May 14 '14 at 03:23

3 Answers3

2

A-Z only checks capital letters. Add also a-z:

[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}
kjhughes
  • 106,133
  • 27
  • 181
  • 240
1

Using RegEx to validate email addresses is difficult.

However, the issue with your code is the casing (as others have pointed out). You can fix it by changing A-Z to A-Za-z, which will check for lowercase and capital letters.

function validate(){
  fieldValue = document.getElementById("check").value;
  pattern = new RegExp(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/);       
  if(pattern.test(fieldValue)){
    alert("true");
  } else {
    alert("false");
  }       
}
Community
  • 1
  • 1
danasilver
  • 556
  • 3
  • 10
  • 2
    If you want lower and uppercase letters use `A-Za-z`, `A-z` is wrong, it includes also the characters `[\]^_\`` which are located between Z and a. – stema May 14 '14 at 06:15
  • @stema Thanks! Since my answer was selected, I updated it to reflect your comment. – danasilver May 14 '14 at 22:40
0

For validating email addresses, this pattern has worked for me for quite some time:

/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/
Pedro
  • 451
  • 2
  • 5
  • 1
    `\w` should not be used in the domain part of the address, since it allows underscore. – Barmar May 14 '14 at 03:24
  • You're only allowing 4-character top-level domains. Didn't you hear the news about new top-level domains earlier this year? There are now many domains that are longer than 4 characters. – Barmar May 14 '14 at 03:27
  • See https://iwantmyname.com/domains/new-gtld-domain-extensions – Barmar May 14 '14 at 03:27