Created
July 8, 2013 10:47
-
-
Save louy/5947841 to your computer and use it in GitHub Desktop.
is_email function from WordPress written in Javascript
This file contains 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
/** | |
* is_email function from WordPress | |
* written in Javascript | |
* | |
* by Louy Alakkad <[email protected]> | |
* | |
* Verifies that an email is valid. | |
* | |
* Does not grok i18n domains. Not RFC compliant. | |
* | |
* @param string $email Email address to verify. | |
* @return string|bool Either false or the valid email address. | |
*/ | |
function is_email( $email ) { | |
// Test for the minimum length the email can be | |
if ( $email.length < 3 ) { | |
return false; | |
} | |
// Test for a single @ character after the first position | |
if ( $email.indexOf('@') === -1 || $email.indexOf('@') !== $email.lastIndexOf('@') ) { | |
return false; | |
} | |
// Split out the local and domain parts | |
var parts = $email.split('@',2); | |
var $local = parts[0], $domain = parts[1]; | |
// LOCAL PART | |
// Test for invalid characters | |
if ( !/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/.test($local) ) { | |
return false; | |
} | |
// DOMAIN PART | |
// Test for sequences of periods | |
if ( /\.{2,}/.test($domain) ) { | |
return false; | |
} | |
// Test for leading and trailing periods and whitespace | |
if ( str_trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) { | |
return false; | |
} | |
// Split the domain into subs | |
var $subs = $domain.split( '.' ); | |
// Assume the domain will have at least two subs | |
if ( 2 > $subs.length ) { | |
return false; | |
} | |
// Loop through each sub | |
for ( i in $subs ) { | |
var $sub = $subs[i]; | |
// Test for leading and trailing hyphens and whitespace | |
if ( str_trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) { | |
return false; | |
} | |
// Test for invalid characters | |
if ( !/^[a-z0-9-]+$/i.test( $sub ) ) { | |
return false; | |
} | |
} | |
// Congratulations your email made it! | |
return $email; | |
function str_trim(str, regex) { | |
var chr = regex.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\:\!\,\=]/g, "\\$&"); | |
return str.replace( new RegExp('/^['+chr+']*/'), '' ).replace( new RegExp('/['+chr+']*$/'), '' ); | |
} | |
} |
The str_trim()
function doesn't seem to work correctly - it doesn't remove leading/trailing hyphens, so it allows [email protected]
through as a valid email, which is then rejected by WordPress.
I replaced it with this function which seems to work: http://phpjs.org/functions/trim/
Hi. @davejamesmiller thank you a lot!
@davejamesmiller That function still appears to let [email protected]
through.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for saving me the hassle of translating that!