How to Validate an E-mail Using JavaScript
To validate an email address using JavaScript, you can use Regular Expressions (RegEx) to check if the input string matches the pattern of a valid email. An email address should start with one or more word characters (letters, digits, or underscores), hyphens, or periods (regex: /^[\w-\.]+/
). It should then proceed with a @
character, then continue with another set of the first part characters (/^[\w-\.+/
), and then it ends with the top level domain (like .com) which is represented by the regex /[\w-]{2,4}$/
function validateEmail(email) {
const res = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
return res.test(String(email).toLowerCase());
}
However, you should not only trust the JavaScript email validation, but you should also validate it on the server-side.
Here’s the above script in action:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js">
</script>
</head>
<body>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='submit' id='validate'>Validate button</button>
</form>
<div id='result'></div>
<script>
function validateEmail(email) {
let res = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
return res.test(email);
}
function validate() {
let result = $("#result");
let email = $("#email").val();
result.text("");
if(validateEmail(email)) {
result.text(email + " is valid");
result.css("color", "blue");
} else {
result.text(email + " is not valid");
result.css("color", "red");
}
return false;
}
$("#validate").on("click", validate);
</script>
</body>
</html>
If you input a valid email address, by clicking on the "validate" button the result will be blue, if you enter an invalid email address then the result will be red.
What is an Email?
An email is a string consist of 3 parts: username, @ symbol and domain. The first part of an email address is the username. @ symbol fits in between the username and the domain of your email address.
The domain consists of two parts: the mail server and the top-level domain. The mail server is the server hosting the email account ("Gmail"). The top-level domain is the extension, such as .com, .net or .info.