Skip to content

Instantly share code, notes, and snippets.

@petermac-
Last active September 12, 2015 19:14
Show Gist options
  • Save petermac-/e5a1849bada82b8d8da1 to your computer and use it in GitHub Desktop.
Save petermac-/e5a1849bada82b8d8da1 to your computer and use it in GitHub Desktop.
isValidEmail.js
function isValidEmail(string){
string = string||'';
var lastseg = (string.split('@')[1]||'').split('.')[1]||'',
input = document.createElement('input');
input.type = "email";
input.required = true;
input.value = string;
return !!(string && (input.validity && input.validity.valid) && lastseg.length);
}
isValidEmail("");// -> false
isValidEmail("asda");// -> false
isValidEmail("asda@gmail");// -> false
isValidEmail("asda@gmail.com");// -> true

Similar to getAbsoluteUrl, you can use a modern browser’s native ability to validate emails from a string by creating an temporary element and testing its validity.

If you wanted to support older browsers you could fall back to trying a regex instead, but with this method you can be ensured that whatever the user’s browser considers to be a valid email, you’re using the exact same logic (however strict or lenient that might be).

http://davidwalsh.name/essential-javascript-functions#comment-502973

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