Skip to content

Instantly share code, notes, and snippets.

@jimmont jimmont/validations.js
Last active Sep 18, 2019

Embed
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();
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
You can’t perform that action at this time.