This Is How To Reduce Repeated Code In jQuery (Validation Form)
As a software developer, one of the fundamental principles you should strive for is writing clean, maintainable code. This not only makes your life easier, but it also ensures that your codebase is easier to understand, debug, and scale in the long run.
When it comes to building validation forms using jQuery, it's common to see a lot of repeated code. This can happen when you need to validate multiple form fields, each with their own set of validation rules. In this article, we'll explore an effective way to reduce this repetition and create a more streamlined validation process.
The Problem with Repeated Code
Imagine you have a contact form with the following fields:
- Name: Required
- Email: Required, must be a valid email address
- Subject: Required
- Message: Required
Typically, the validation logic for these fields would look something like this:
// Le nom n'a pas été entré
if ($sendername.val() === "") {
showError($sendername, 'Veuillez entrer votre nom');
}
// Le courriel est absent ou invalide
if ($senderemail.val() === "") {
showError($senderemail, 'Veuillez entrer une adresse de courriel');
} else if (!emailReg.test($senderemail.val())) {
showError($senderemail, 'Votre adresse courriel semble invalide');
}
// Le sujet n'a pas été entré
if ($sendersubject.val() === "") {
showError($sendersubject, 'Veuillez écrire un commentaire');
}
// Le commentaire n'a pas été entré
if ($sendermessage.val() === "") {
showError($sendermessage, 'Veuillez écrire un commentaire');
}
This code works, but it has a few problems:
- Repetition: The validation logic for each field is nearly identical, leading to a lot of repetitive code.
- Maintainability: If you need to change the validation logic for one field, you'll have to update the code in multiple places.
- Readability: The code can become difficult to read and understand, especially as the number of form fields grows.
These issues can make your codebase harder to work with, and they can also make it more prone to bugs and errors.
The Solution: A Reusable Validation Function
To address these problems, we can create a reusable function that encapsulates the validation logic. This function will take two parameters: the form field element and the error message to display.
Here's what the function might look like:
function showError(el, err) {
el.addClass('commenterrorfield').after("<span class='commenterror'>" + err + "</span>");
el.on('click focusin', function() {
$(this).removeClass().next("span").attr('class', 'commenterror-hide');
});
errors = true;
}
This function performs the following actions:
- Adds a CSS class (
commenterrorfield
) to the form field element to indicate that there is an error.
- Inserts a span element with the error message and a CSS class (
commenterror
) after the form field.
- Attaches a click and focus event listener to the form field, which removes the error class and hides the error message when the field is clicked or focused.
- Sets a global variable
errors
to true
to indicate that there are validation errors.
Now, we can use this function to validate our form fields like this:
// Le nom n'a pas été entré
if ($sendername.val() === "") {
showError($sendername, 'Veuillez entrer votre nom');
}
// Le courriel est absent ou invalide
if ($senderemail.val() === "") {
showError($senderemail, 'Veuillez entrer une adresse de courriel');
} else if (!emailReg.test($senderemail.val())) {
showError($senderemail, 'Votre adresse courriel semble invalide');
}
// Le sujet n'a pas été entré
if ($sendersubject.val() === "") {
showError($sendersubject, 'Veuillez écrire un commentaire');
}
// Le commentaire n'a pas été entré
if ($sendermessage.val() === "") {
showError($sendermessage, 'Veuillez écrire un commentaire');
}
As you can see, the validation logic for each field is much more concise and easier to read. If you need to change the validation logic for a field, you only need to update the code in one place.
Extending the Reusable Validation Function
You can further extend the reusable validation function to make it even more powerful and flexible. For example, you could add support for different types of validation (e.g., number, date, password) or allow the function to handle multiple error messages for a single field.
Here's an example of how you might extend the function:
function validateField(el, rules) {
let isValid = true;
const errors = [];
for (const rule of rules) {
switch (rule.type) {
case 'required':
if (el.val() === '') {
errors.push(rule.message);
isValid = false;
}
break;
case 'email':
const emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(el.val())) {
errors.push(rule.message);
isValid = false;
}
break;
case 'number':
if (isNaN(el.val())) {
errors.push(rule.message);
isValid = false;
}
break;
// Add more validation types as needed
}
}
if (!isValid) {
showError(el, errors.join(', '));
}
return isValid;
}
In this extended version, the validateField
function takes two parameters: the form field element and an array of validation rules. Each rule has a type
and a message
property.
The function loops through the validation rules, checks the field's value against the rule type, and adds any errors to an array. If there are any errors, the function calls the showError
function to display them.
You can use this extended function like this:
const validationRules = [
{ type: 'required', message: 'Veuillez entrer votre nom' },
{ type: 'email', message: 'Votre adresse courriel semble invalide' },
{ type: 'required', message: 'Veuillez écrire un commentaire' },
];
if (!validateField($sendername, validationRules)) {
// Handle validation errors
}
if (!validateField($senderemail, validationRules)) {
// Handle validation errors
}
if (!validateField($sendermessage, validationRules)) {
// Handle validation errors
}
This approach makes it easier to add, remove, or modify validation rules for each form field without having to change the validation logic in multiple places.
Conclusion
By creating a reusable validation function, you can significantly reduce the amount of repeated code in your jQuery-based validation forms. This not only makes your codebase more maintainable and easier to read, but it also allows you to easily extend the validation logic as your application grows.
Remember, writing clean, modular code is an essential skill for any software developer. By following best practices like this, you can create more robust and scalable applications that are a joy to work with.
For more information on how Flowpoint.ai can help you identify technical errors and generate recommendations to improve your website's conversion rates, visit Flowpoint.ai
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.