From the pure security and efficiency point of view, client-side validation is completely useless due to evident reasons. In that vein, validating an e-mail address with or without regular expressions makes no difference. In fact, a proper regular expression to validate e-mails should be RFC-compliant. The problem is that such a regular expression is incredibly complex and long to be written, not to say that JavaScript regular expressions are the less suitable to this particular task. Client-side validation should only try to catch macroscopic errors made by users during form submission but it should never be a catch-all for all possible errors. JavaScript can be turned off: that's why this kind of validation is purely cosmetic. It's a pseudo-validation. Let's see how to try to "validate" e-mails without regular expressions.
We can split an e-mail address into parts and check whether such components are present:
var checkEmail = function(value) {
var valid = true;
if (value.indexOf('@') == -1) {
valid = false;
} else {
var parts = value.split('@');
var domain = parts[1];
if (domain.indexOf('.') == -1) {
valid = false;
} else {
var domainParts = domain.split('.');
var ext = domainParts[1];
if (ext.length > 4 || ext.length < 2) {
valid = false;
}
}
}
return valid;
};
This should catch only gigantic typos made by users, nothing more. Here's an example:
var form = document.getElementById('test');
var validate = function(event) {
event.preventDefault();
var val = document.getElementById('email').value;
var valid = checkEmail(val);
if (!valid) {
alert('Not a valid e-mail address');
} else {
alert('Valid e-mail address');
}
};
form.addEventListener('submit', validate, false);
You can see the demo below.