JavaScript Email Validation
Regular Expression for Validating Email in JavaScript
If your HTML form accepts an email field, it is a good practice to validate the email before the form is submitted. It is also mandatory to re-validate all user input, including emails for validity at the serverside. In case you are using Node.js, you can use the same regular expression function below to validate emails both on the clientside and the serverside.
Function for validating email address
function validateEmail(email) {
// First check if any value was actually set
if (email.length == 0) return false;
// Now validate the email format using Regex
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
return re.test(email);
}
The above regular expression is a generic email validator, it may fail for some very rare but valid emails. But it should serve you well for emails used by common people like you and me.
Example code for validating an email
Validating the email, before it is submitted at the clientside.
var email = document.getElementById('email');
if (validateEmail(email)) { alert('Valid email address'); }
else { aler('Invalid email address'); }
Validating the email again at the serverside using Node.js.
var email = req.params.email;
if (validateEmail(email)) { console.log('Valid email address'); }
else { console.log('Invalid email address'); }
Exercise
- Which valid email addresses would fail to validate using the above function?
- Why don't we use JavaScript's
match
orexec
methods to validate the email address?
References
Make a Comment