Last active
September 24, 2015 05:03
-
-
Save jayphelps/383ebea655091f2aebae to your computer and use it in GitHub Desktop.
Validates an email, error on the side of letting bad ones through (best practice). Accepts emails with plus signs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValidEmail(str) { | |
/** | |
* These comments use the following terms from RFC2822: | |
* local-part, domain, domain-literal and dot-atom. | |
* Does the address contain a local-part followed an @ followed by a domain? | |
* Note the use of lastIndexOf to find the last @ in the address | |
* since a valid email address may have a quoted @ in the local-part. | |
* Does the domain name have at least two parts, i.e. at least one dot, | |
* after the @? If not, is it a domain-literal? | |
* | |
* This WILL ACCEPT some invalid email addresses BUT | |
* it doesn't reject valid ones, which is most important to us | |
* as this should just be used to prevent gibberish input. | |
* | |
* Reference: http://tools.ietf.org/html/rfc2822 | |
*/ | |
// First, make sure the string isn't empty/falsy | |
if (!str) { | |
return false; | |
} | |
var atSymbol = str.lastIndexOf('@'); | |
// no local-part | |
if (atSymbol < 1) { | |
return false; | |
} | |
// no domain | |
if (atSymbol === str.length - 1) { | |
return false; | |
} | |
// there may only be 64 octets in the local-part | |
if (atSymbol > 64) { | |
return false; | |
} | |
// there may only be 255 octets in the domain | |
if (str.length - atSymbol > 255) { | |
return false; | |
} | |
// Is the domain plausible? | |
var lastDot = str.lastIndexOf('.'); | |
// Check if it is a dot-atom such as example.com | |
if (lastDot > atSymbol + 1 && lastDot < str.length - 1) { | |
return true; | |
} | |
// Check if could be a domain-literal. | |
if (str.charAt(atSymbol + 1) === '[' && str.charAt(str.length - 1) === ']') { | |
return true; | |
} | |
// If you reach here we just give up and say no | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment