How to Validate an E-mail Using JavaScript
Read this tutorial and learn a fast and easy solution to the issue of validating an email using JavaScript. Also, you will read about what the email is.
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. The pattern verifies that the address starts with valid characters, includes an @ symbol, a domain name, and a top-level domain. The regex used is /^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$/.
Javascript valid email using regex
function validateEmail(email) {
const res = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$/;
return res.test(String(email).toLowerCase());
}Client-side validation improves user experience, but you should always validate email addresses on the server-side for security.
Here’s the above script in action:
Javascript/ Jquery email validation
<!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='button' id='validate'>Validate button</button>
</form>
<div id='result'></div>
<script>
function validateEmail(email) {
let res = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$/;
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", function(e) { e.preventDefault(); 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 consisting of three parts: the username, the @ symbol, and the domain. The @ symbol separates the username from the domain.
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.