0

I am trying to validate a form to ensure that the entered email address value is in the correct format. I have everything working except checking that it only contains one '@' symbol. This is my code so far

var x = document.forms["registration"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
    alert("Not a valid e-mail address");
    return false;
BrownEye
  • 979
  • 2
  • 12
  • 21
  • 1
    I'm genuinely asking, just incase it's something you've overlooked, but does the simple HTML5 `type="email"` provide that kind of check to the input? I know it changes the keyboard layouts on mobile devices, but what kind of validation does it perform? – Lee Sep 16 '14 at 12:38
  • why not use a regex to validate the email address instead. See here: http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – ChaoticNadirs Sep 16 '14 at 12:39
  • @Lee according to the w3c, the user agents should implement email validation: "The user agent should act in a manner consistent with expecting the user to provide a single e-mail address" [source](http://www.w3.org/TR/html5/forms.html#e-mail-state-(type=email)). However, according to [caniuse](http://caniuse.com/#feat=form-validation), some browsers do not currently support it. – Sir Celsius Sep 16 '14 at 12:43

3 Answers3

2

To check and validate for single '@'. The below mentioned one is the standard Email Regex which is been used:

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
Nad
  • 4,605
  • 11
  • 71
  • 160
  • How can I use this to also check for the domain name? I need to ensure that the user is registering from only one domain (e.g. peter@google.com or mary@google.com) – BrownEye Sep 16 '14 at 12:47
  • 1
    Your question did not merely covered the domain section. See your question. I covered your first point that it will not take more than one '@'. Post it in new question. – Nad Sep 16 '14 at 12:59
  • Okay sorry, Is there a quick way I can add a section to my code to check for double '@' symbols? or regex the only sensible way? considering I also need to check the domain – BrownEye Sep 16 '14 at 13:02
  • See the regex for domain (^(?:[a-zA-Z0-9]+(?:\-*[a-zA-Z0-9])*\.)+[a-zA-Z]{2,6}$). u need to match a pair with checking only one @. I suggest to use javascript for matching both – Nad Sep 16 '14 at 13:15
0

Use a regex like this to validate email: ^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,4})$

Using a regular expression to validate an email address

Community
  • 1
  • 1
SanRyu
  • 210
  • 1
  • 2
  • 13
0

Use the regex

var atpos = (x.match(new RegExp("@", "g")) || []).length;

theLaw
  • 1,261
  • 2
  • 11
  • 23