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 domainEndsWithDash@domain-.com
would be validlocal@SecondLevelDomainNamesAreInvalidIfTheyAreLongerThan64Charactersss.org
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 = 'some.name@some.domain.com';
if (!useremail.isEmail())
alert('Please check your email');
else
alert('Thank you for your email');
Update: Modified the Regex to reject underscore characters in the domain part.