Skip to content

Instantly share code, notes, and snippets.

@jimmont
Last active September 18, 2019 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmont/aaa946e035875270f2c7179aaec11c7f to your computer and use it in GitHub Desktop.
Save jimmont/aaa946e035875270f2c7179aaec11c7f to your computer and use it in GitHub Desktop.
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();
try{
// 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}"`);
}catch(err){
console.error(`probably not an email address: "${email}"`, err);
};
return isValid;
}
[
'user+this@はじめよう.みんな'
, 'stuff@things'
, 'user+that@host.com'
, 'Jean+François@anydomain.museum','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, '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