Most of the time we used to validate the single form and display error messages according to the input fields. You can create a single event that will validate all your website’s forms and will display the error messages also.
Simply create a function that will work on your top parent container element, find all the input elements into that container and validate the field if required otherwise ignore that. You can even count the errors also and show the total number of errors on the top of your form.
Validations would be by the type of input field like
- Empty and maxlength in case of text type
- Check any option selected in case of radio
- Check empty and valid format in case of email
- Check number format, empty, minimum and maximum in case of number
- Empty, minimum and maximum in case of date
Note: Above tests are the basic requirements, you can add more according to your task.
Below is the format of the function that will loop through all your input elements in container element and count the errors. This is only the format; we need to write the validation scripts for required input types.
function validateRequiredFields(containerElement) {
var totalEmptyInput = 0;
$(containerElement).find('input').each(function () {
//validation script for all input types
}
}
Not all the form fields are input fields, there are others also like select, textarea etc. So our function will have more loop accordingly as below code.
function validateRequiredFields(containerElement) {
var totalEmptyInput = 0;
$(containerElement).find('input').each(function () {
//validation script for all input types
}
$(containerElement).find('textarea').each(function () {
}
$(containerElement).find('select').each(function () {
}
}
To validate the text type, we can use the code below, you can use extra validations/regex if you have some more requirements. This is just checking the errors and will add a error span after your input element.

Validate file:

Validate email: in case of email, I have also checked the email format by isEmail function. I have provide this function that is using a regex expression to validate the email format.

function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Place this validateRequiredFields function in common JavaScript file and integrate into your layout so that this can be used in whole website. We can validate any form by calling this function with container div element like:
let validate = validateRequiredFields('#divParent');
Here i am passing the id selector, you can also pass class selector but developers should use id selector mostly for this type of functionality.