0

I want there to only be one at sign allowed in the email address and also to only contain ( a-z,A-Z, underscores (_), dot(.) and dash (-)). This is what i have so far. Thanks

var email = document.forms["register"]["email"].value;
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");

if (atpos < 3 || dotpos < atpos + 4 || dotpos + 2 >= email.length)
{                   
    alert("You have not entered a valid Email address, please check for mistakes and re-submit");
    return false;
}
Chris Moutray
  • 18,029
  • 7
  • 45
  • 66

1 Answers1

-2

What you want is something called a regular expression. Basically you can specify a pattern and have javascript check your input to see if it matches that pattern. The following javascript function should return true is the input is a valid email address, though there are a lot of topics out there that discuss which regular expression is best for this exact purpose.

function emailIsValid(email) { 
    var regex = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return regex.test(email);
} 
Maloric
  • 5,525
  • 3
  • 31
  • 46
  • It's much more complicated than that. See http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – ya23 May 15 '13 at 14:05
  • The regex can be a lot more complex, but there has to be a balance between "will it validate every single email address in the world" and "will I ever need it to be that accurate". The regex I provided is acceptable and will work 99% of the time. Understanding that some people would prefer a more accurate solution, however, I did point out that there are a lot of discussions on which regex is the best to use. – Maloric May 15 '13 at 14:23
  • 1
    @Maloric yes, and that has been thoroughly discussed on SO multiple times. Which is why you are getting downvoted. – Ryan May 15 '13 at 14:29