Anjan Dutta

How to do an Email Validation in JavaScript

How to do an Email Validation in JavaScript

We can validate an email in javascript using the RegEx pattern match.

This is the best way of doing email validation in javascript.

The best part is, we can customize the RegEx as per our requirement to add any custom rule.

See the working code below.


<title>Email validation</title>
<form name="myForm" novalidate onsubmit="return false;">
<label for="e_input">Enter Email</label>
<input type="email" name="e_input" id="e_input" required>
<button type="submit" onclick="validateEmail(document.getElementById('e_input').value)">Submit</button>
Checkout my <a href="">blog</a> for more tutorial.

In above code, the <form> tag has these attributes novalidate onsubmit="return false;". The novalidate disables default HTML form validation and the onsubmit="return false;" stops the form submit event and lets the validation function run.

The JavaScript

function validateEmail(email) {
const emailValidatorRegEx = /^(([^<>()[\]\\.,;:\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,}))$/;
let result = emailValidatorRegEx.test(String(email).toLowerCase());
let isValid = result==true?"a valid ": "an invalid ";
console.log(email + " is " + isValid + "email");