Step-by-step procedure for form validation using JavaScript
1. HTML Form
Create an HTML form with input fields that you want to validate.
Add the required attribute to make sure the user fills in the mandatory fields.
JavaScript
<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>
2. JavaScript Validation Function
Create a JavaScript function to validate the form.
This function will be triggered when the user clicks the submit button.
JavaScript
function validateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
// Perform individual field validations
if (name.trim() === '') {
alert('Please enter your name.');
return false;
}
if (!isValidEmail(email)) {
alert('Please enter a valid email address.');
return false;
}
// If all validations pass, the form can be submitted
return true;
}
function isValidEmail(email) {
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
3. Submit Button Event
Add an event listener to the form’s submit button to trigger the validation function when the user submits the form.
JavaScript
document.getElementById('myForm').addEventListener('submit', function (event) {
if (!validateForm()) {
event.preventDefault(); // Prevent form submission if validation fails
}
});
When the user clicks the submit button, the validateForm() function is called. It retrieves the values of the form fields and performs individual validations. If any validation fails, an alert is shown, and the form submission is prevented using event.preventDefault(). If all validations pass, the form will be submitted as usual.