In this blog, we are going to see how to Validate an Email ID using JavaScript. Validating an Email ID is a common task in web development. As Email ID validation is an essential feature in web forms to ensure users provide correctly formatted email addresses. This can be achieved effectively using JavaScript in combination with HTML. Below, we will explore how to create a simple email validation script using JavaScript.
JavaScript for validation
JavaScript is used to add interactivity to the form, including the logic for email validation. The script will define two functions: one for validating the email format using an regular expression and another for handling the form submission.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Email Validation</title> <script> function validateEmail(email) { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return regex.test(email); } function validateForm() { const emailInput = document.getElementById("email").value; const isValid = validateEmail(emailInput); if (isValid) { alert("Valid email address!"); } else { alert("Invalid email address!"); } return false; } </script> </head> <body> <form onsubmit="return validateForm()"> <label for="email">Email:</label> <input type="text" id="email" name="email"> <input type="submit" value="Validate"> </form> </body> </html>
Explanation for above code
HTML Form Structure:
The form includes a label, a text input for the email, and a submit button. The onsubmit attribute of the form specifies that the validateForm() JavaScript function should be called when the form is submitted.
JavaScript Validation:
validateEmail(email): This function uses a regular expression to check if the provided email string matches a basic email format. regex.test(email): Tests if the email matches the regular expression. Returns true if it does, and false otherwise.
function validateEmail(email) { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return regex.test(email); }
validateForm(): This function retrieves the value of the email input field, checks its validity using validateEmail(), and displays an alert based on the validation result. It also prevents form submission by returning false.
function validateForm() { const emailInput = document.getElementById("email").value; const isValid = validateEmail(emailInput); if (isValid) { alert("Valid email address!"); } else { alert("Invalid email address!"); } return false;
Regular Expression (Regex):
The regular expression used for validating the email is ^[^\s@]+@[^\s@]+\.[^\s@]+$.
Output:
sreeja is an Invalid email address! [email protected] is an valid email address!