Javascript: Near perfect Email validation / check routine as string prototype


Based on this post and that post i created a simple string prototype to evaluate emails via one Javascript RegEx in Javascript.

In the past i used a complex check that also had a list of all valid TLDs integrated. Now every time a new TLD (like .biz or .mobi) was introduced i had to update the email check routine. Too much work imho.

Based on that and the limitations of the JS RegEx engine this will result in only three issues i can perfectly live with:

  • Any TLD will be accepted (e.g. somename@domain.invalidtld) would be a valid email
  • would be valid
  • would be valid

Here is the String prototype:

String.prototype.isEmail = function () {
    validmailregex = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9][-a-z0-9]*(\.[-a-z0-9]+)*\.([a-z][a-z]+)|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
    return validmailregex.test(this);

Now to validate and email you can simply do this:

// Checks the email of a user
var useremail = '';
if (!useremail.isEmail())
    alert('Please check your email');
    alert('Thank you for your email');

Update: Modified the Regex to reject underscore characters in the domain part.

If you've read this far you might as well follow me on Twitter here.