0

I am using a regex to validate an email address in JavaScript.

The regex is pretty simple. It checks three things: 1)'@' , 2)'.' ('dot' as in something@gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)

Here is the code:

function checkemail(){
  var e = document.getElementById("email").value;
  if((e.match(/@/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
  //display error message
  }
}

My question is:

(e.match(/./g)==null); //returns false even though there are no dots in the string e

returns false even when there are no dots in string.

For example:

("thisIsMyEmail".match(/./ig))==null //returns false

Why does it return false when it should be true?

raneshu
  • 702
  • 2
  • 15
  • 39

4 Answers4

5

/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."

For an actual dot, escape it with a backslash: /\./g.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
2

First off, you don't need to check if the string is null. Simply use this:

var email = "Godisgood@gmail.com";

if (email.match(/^\S+\@\S+\.\S+$/i)){
alert("Email address passed validation.");
}
Drazzah
  • 7,371
  • 7
  • 31
  • 57
  • Thanks for your response. It does pretty much the same as mine. It does not seem to check for letters after the final dot. Eg: bob@gmail. returns true. But it helps. Thanks – raneshu Dec 06 '14 at 17:18
  • @raneshu, I'm sorry, my code was a bit messy. Try it now. – Drazzah Dec 06 '14 at 20:32
1

Try this

(e.match(/\./g)==null);

. matches any character so needs escaping /\./g

Oleksandr T.
  • 73,526
  • 17
  • 164
  • 143
1

you have to escape the . The unescaped period means matches any character.

Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.

In your snippet the correct answer is

(e.match(/\./g)==null);

This should result to what you're expecting

Carlo Gonzales
  • 365
  • 2
  • 9