First, make sure your HTML form has the necessary fields and a submit button. For example:
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
Next, you’ll need to create a JavaScript function that will handle the form submission and perform validation. Place this script just before the closing </body>
tag in your HTML document:
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
// Prevent the form from submitting automatically
event.preventDefault();
// Get the values from the form
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
// Perform validation
if (name === "") {
alert("Please enter your name.");
return false; // Prevent form submission
}
if (!isValidEmail(email)) {
alert("Please enter a valid email address.");
return false; // Prevent form submission
}
// If all validation passes, you can submit the form
// You can add additional processing code here
// For demonstration purposes, let's alert a success message
alert("Form submitted successfully!");
});
// Function to validate email format
function isValidEmail(email) {
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(email);
}
</script>
In the above code:
- We use
addEventListener
to attach a JavaScript function to the form’s submit
event.
- Inside the event handler function, we prevent the form from submitting automatically using
event.preventDefault()
.
- We retrieve the values of the name and email fields.
- We perform validation checks:
- Check if the name field is empty.
- Check if the email field matches a valid email pattern using a regular expression (
isValidEmail
function).
- If any validation check fails, we display an alert message and return
false
to prevent form submission.
- If all validation checks pass, you can add your custom processing code (e.g., sending data to a server) or simply submit the form.
This code provides basic client-side validation for your form. You can customize it further according to your specific requirements.