JavaScript Email Validation
JavaScript can be used to validate an email.
Several criteria must be followed to validate an email ID, such as:
* An email ID must include the `@` and `.`
characters.
* There must be at least one character both before
and after the `@` symbol.
* There must be at least two characters after the `.`2
(dot).
Example
Let's look at a simple example to validate the email field.
<!DOCTYPE
html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Email
Validation Example</title>
<script
type="text/javascript">
function
validateForm() {
var
email =
document.forms["myForm"]["email"].value;
var
emailPattern =
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
// Check if the email field is empty
if (email == "") {
alert("Email must be
filled out");
return false;
}
// Check if the email matches the pattern
if (!emailPattern.test(email)) {
alert("Please enter a
valid email address");
return false;
}
return true;
// Allow form submission if validation passes
}
</script>
</head>
<body>
<h2>Email Validation Example</h2>
<form name="myForm"
action="/submit" method="post" onsubmit="return validateForm()">
<label
for="email">Email:</label>
<input type="text" id="email"
name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>