Skip to content

Instantly share code, notes, and snippets.

@louy
Created July 8, 2013 10:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louy/5947841 to your computer and use it in GitHub Desktop.
Save louy/5947841 to your computer and use it in GitHub Desktop.
is_email function from WordPress written in Javascript
/**
* is_email function from WordPress
* written in Javascript
*
* by Louy Alakkad <me@l0uy.com>
*
* 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+']*$/'), '' );
}
}
@d13r
Copy link

d13r commented May 22, 2014

Thank you for saving me the hassle of translating that!

@d13r
Copy link

d13r commented May 22, 2014

The str_trim() function doesn't seem to work correctly - it doesn't remove leading/trailing hyphens, so it allows dave@abc.x- 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/

@korobochkin
Copy link

Hi. @davejamesmiller thank you a lot!

@tdmalone
Copy link

@davejamesmiller That function still appears to let dave@abc.x- through.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment