0

Using JSLint I can't get my isEmailValid working, what is wrong with the code? I get different error messages like local was not defined before it was used or @ invalid character or ^ is not enclosed but for the email it could have the symbol "^"?

function isEmailValid(email) {
"use strict";
var e = (email.split("@"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);
if (e.length !== 2) {
    return false;
}
if (local.test(e[0])) {
    return false;
}
if (e[0].length > 253) {
    return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
    return false;
}
if (domain.test(e[1])) {
    return false;
}
if (e[1].length > 253) {
    return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
    return false;
}
return true;
    }
Homer Homer
  • 57
  • 1
  • 2
  • 7
  • 2
    [Stop Validating Email Addresses With Your Complex Regex](http://davidcelis.com/blog/2012/09/06/stop-validating-email-addresses-with-regex/) – Denys Séguret Oct 17 '12 at 18:48
  • [related question](http://stackoverflow.com/questions/2372635/purpose-of-jslint-disallow-insecure-in-regex-option) – jbabey Oct 17 '12 at 18:51

3 Answers3

1

Validate email addresses client-side with this regular expression:

/.@./

And then do the real validation server-side by sending an email to that address.

Working email addresses can and do exist that do not conform to any spec. There's no sense restricting users because their valid email address looks wrong, while at the same time allowing users to enter email addresses that look right, but are fake (eg, iwontgiveyoumyrealemailaddress@noreply.com looks real to a computer, but probably isn't).

Required reading

Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176
0

I would suggest using regex:

function validateEmail(email) { 
   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,}))$/;
   return re.test(email);
} 

See also: Validate email address in JavaScript?

Community
  • 1
  • 1
Arend
  • 3,741
  • 2
  • 27
  • 37
0

You're getting the error about local because you're not actually declaring it as a local variable within the function.

var statements don't contain or use parenthesis. So, using them anyways as:

var e = (email.split("@"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/);

Is equivalent to:

local = /[^\w.!#$%&*+-\/=?^_{|}~]/;
domain = /[^\w.-]/;
var e = (email.split("@"), local, domain);

e will then be set to the result of the parenthesis being evaluated, which simply contain operands for comma operators. So, the last line is equivalent to:

email.split("@");
local;
var e = domain;

And, as that doesn't seem to be what you wanted, you probably don't want the parenthesis:

var e = email.split("@"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[^\w.-]/;
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199