Last active
August 29, 2015 14:07
-
-
Save qgustavor/be02608692116ab963ca to your computer and use it in GitHub Desktop.
isValidEmail
This file contains 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
/** | |
* Validates e-mail addresses | |
* Supports internacionalized e-mails | |
*/ | |
function isValidEmail(input) { | |
// Split the e-mail into local part and domain part: | |
var parts = input.split('@'); | |
// It needs to have those two parts: | |
if (parts.length !== 2) return false; | |
// Remove comments: | |
var commentRegex = /(^\([^\)]*\)|\([^\)]*\)$)/g; | |
parts[0] = parts[0].replace(commentRegex, ''); | |
parts[1] = parts[1].replace(commentRegex, ''); | |
// Ensure domain part and that it doesn't exceed 256 characters | |
// and consist only on valid characters: | |
if (!parts[1] || parts[1].length >= 256 || | |
!(/^(?:[\u007F-\uffff]|[\w\-\.])+$/i.test(hostnameParts[i]))) return false; | |
// Split the hostname into parts: | |
var hostnameParts = parts[1].split('.'); | |
if (!hostnameParts.length) return; | |
for (var i = 0; i < hostnameParts.length; i++) { | |
// Each part needs to be between 1 to 63 characters | |
if (!hostnameParts[i] || hostnameParts[i].length > 63) { | |
return false; | |
} | |
} | |
// The local part need to exist, can't start or end with a dot, neither have two consecurive dots: | |
if (!parts[0] || | |
parts[0].charAt(0) === '.' || | |
parts[0].charAt(parts[0].length - 1) === '.' || | |
parts[0].indexOf('..') !== -1) { | |
return false; | |
} | |
// "(),:;<>@[\] and spaces are only allowed between quotes: | |
if (/[\s"(),:;<>@\[\\\]]/.test(parts[0].replace(/(^|\.)"((?:[^"\\]|\\"|\\)+)"((?=\.)|$)/g, '.'))) { | |
return false; | |
} | |
// Otherwise it's a valid e-mail: | |
return true; | |
} |
New update has better rules for hostnames while still accepting IDNs. Maybe it's possible to improve the comment removing steps.
It doesn't validates e-mails with @ in the local part, like "@ 1145 jan 31"@example.com . As this function tries to follow the RFCs it needs to be fixed.
A warning: Gmail, which considers those e-mails valid, have bugs when sending e-mails to e-mails like that. Same for e-mails with < and > in the local part: seems the parser used to extract the address from the header doesn't handle those cases.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Checking for spaces and at least a dot isn't a good check for the domain part, eg: domains can't have underscores too.
If someone have a javascript function for validating IDNs then it's possible to fix that replacing lines 17-22 with
if (!isHostname(parts[1])) return false;
Maybe a good solution is using punycode.js and the old school hostname validation regexes.