Skip to content

Instantly share code, notes, and snippets.

Last active September 18, 2019 17:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
validate email addresses, dates, etc in JavaScript
take an approach leveraging the platform implementation's internal parser for things to validate,
if it works in these on the user-experience side confirm the input is as-intended
possibly by entering the same value twice or similar user-controlled validation
email and date validation is too complex for pattern matching;
function validEmail(email=''){
var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
email = email.trim();
// handles punycode, etc using browser's own maintained implementation
url = new URL('http://'+email);
$0 = `${url.username}@${url.hostname}`;
isValid = emailPatternInput.test( email );
if(!isValid) throw 'invalid email pattern on input:' + email;
isValid = emailPatternUrl.test( $0 );
if(!isValid) throw 'invalid email pattern on url:' + $0;
console.log(`email looks legit "${email}" checking url-parts: "${$0 === email ? '-SAME-':$0}"`);
console.error(`probably not an email address: "${email}"`, err);
return isValid;
, 'stuff@things'
, ''
, 'Jean+Franç','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, 'not@@really'
, 'no'
].forEach(email=>console.log(validEmail(email), email));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment