Last active
September 18, 2019 17:44
-
-
Save jimmont/aaa946e035875270f2c7179aaec11c7f to your computer and use it in GitHub Desktop.
validate email addresses, dates, etc in JavaScript
This file contains hidden or 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
/* | |
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' | |
, '[email protected]' | |
, 'Jean+Franç[email protected]','هيا@יאללה' | |
, '试@例子.测试.مثال.آزمایشی' | |
, '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