-5

What is wrong with my code? I can't find the solution.

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

var email= document.getElementById("email").value;

if (re.test(email) == false) {  
    document.getElementById("email").focus();
    return false;
}

The double quotes caused the problem, thank you! I cant vote up because of my reputation :-(

Jim Bamboo
  • 43
  • 4
  • why so complicated? [`see here`](http://stackoverflow.com/search?q=email+validation+javascript&submit=search) – xkeshav Aug 24 '12 at 09:08
  • 3
    You tell *us* what's wrong. Do you get an error? Does it not validate correctly? Does it pass all input, or does it not pass any valid emails, or does it give false positives/negatives? – JJJ Aug 24 '12 at 09:10
  • duplicate http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – yogi Aug 24 '12 at 09:11
  • Holy moley! That's a complex validation you have there! – Marcos Placona Aug 24 '12 at 09:15

2 Answers2

1

Like suresh suggested, you should remove the quotes (") around your regex string. So your first line should be:

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

I produced a working example below:

<script>
function test()
{
  var re = /^(([^<>()[\]\\.,;:\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,}))$/;
  var email= "test@somedomain.com";

  if (re.test(email) == false) {  
    alert("invalid email address");
    return;
  }
  alert("valid address");
}
</script>
<button onclick="test()">TEST</button>
Fatih
  • 308
  • 1
  • 10
-1

Lets try this once which is working smart for me

  function IsEmail(email) {
                var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                return regex.test(email);
             }

if(!IsEmail(mailString)){
                $("#somediv").text(" Email should be valid ");
                return false;
                }
  • People - the question is "What is wrong with **my** code". It's *not* "how to validate email addresses". – JJJ Aug 24 '12 at 09:39
  • @jim bamboo ..remove the "" to your regex string . –  Aug 24 '12 at 09:43