How to Validate an E-mail Using JavaScript
Validating an email is very hard but a possible thing. In this tutorial, we will show how to validate an email using JavaScript.
To get a valid email id, the best way is using regex:
function validateEmail(email) {
const res = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/;
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+([\.-]?\w+)*(\.\w{2,3})+$/;
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.