Skip to content

Instantly share code, notes, and snippets.

@qgustavor
Last active August 29, 2015 14:07
Show Gist options
  • Save qgustavor/be02608692116ab963ca to your computer and use it in GitHub Desktop.
Save qgustavor/be02608692116ab963ca to your computer and use it in GitHub Desktop.
isValidEmail
/**
* 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;
}
@qgustavor
Copy link
Author

New update has better rules for hostnames while still accepting IDNs. Maybe it's possible to improve the comment removing steps.

@qgustavor
Copy link
Author

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