Validating email addresses is an essential part of web development to ensure that users provide a correctly formatted email. JavaScript provides a way to perform this validation on the client side. Below is an explanation of how to validate email addresses using JavaScript, including the criteria that need to be met.
1. Contain @ and . Characters: The email must include both @ and . characters.
2. At Least One Character Before and After @: There should be at least one character before and after the @ symbol.
3. At Least Two Characters After . (Dot): There should be at least two characters after the dot.
Email validation ensures that the user inputs a properly formatted email address.
<script>
function validateEmail() {
var email = document.forms["emailForm"]["email"].value;
var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(email)) {
alert("Invalid email format");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="emailForm" onsubmit="return validateEmail()" method="post">
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>