In the third article of the "jQuery validation" series, you will learn how to apply validation to checkboxes in a form. There are two types of "checkboxes" in an HTML form, "single checkbox" and "group checkbox".
A "single checkbox" has just one checkbox, just like a login form, remember.
A "group checkbox" has multiple checkboxes, like job type, language, etc. Job types have "full time", "part-time", etc.
Validation scenarios
This validation scenario depends on the type of checkbox. If the checkbox is of a single type, only the required validation will be applied. But if the checkbox is of group type, then "required validation", and "minimum or maximum validation" can be applied.
Ways to implement validation
You can use custom logic to apply validation or the "serializeArray" function can be used.
Checkbox Validation
First, look at this HTML code which contains the code of a form which contains the code of a checkbox.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RAYS CODING : Checkbox Validation</title>
<link rel="stylesheet" href="../style.css">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-zinc-950 flex justify-center">
<section class="w-auto h-auto mt-28 bg-white">
<header class="bg-violet-600 p-5 pl-6 pr-6">
<h2 class="text-3xl text-white tracking-wider">RAYS CODING : jQuery Checkbox Validation</h2>
</header>
<form action="#" method="post" class="p-5">
<Label>Language</Label>
<div class="mt-5">
<label class="block">
<input type="checkbox" name="languages[]" value="english" class="language-checkbox">
English
</label>
<label class="block">
<input type="checkbox" name="languages[]" value="spanish" class="language-checkbox">
Spanish
</label>
<label class="block">
<input type="checkbox" name="languages[]" value="french" class="language-checkbox">
French
</label>
<label class="block">
<input type="checkbox" name="languages[]" value="german" class="language-checkbox">
German
</label>
<label class="block">
<input type="checkbox" name="languages[]" value="chinese" class="language-checkbox">
Chinese
</label>
</div>
<div class="mt-5 bg-red-300 p-3 text-red-950 hidden" id="message"></div>
<button type="submit" class="mt-5 bg-violet-600 p-3 w-full text-white font-semibold tracking-wider" id="submit-button">SUBMIT</button>
</form>
</section>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>
This code is a simple HTML form that includes a checkbox to select the language of your choice. Inside the form is a language section that includes a few (e.g. English, Spanish, French, German, and Chinese). Each checkbox is given a label that tells which language it is selecting. The purpose of this form is to provide a document in one or more languages.
The code also has a validation mechanism wherein if no one selects any of the checkboxes, a red sexy box appears telling the users that at least one checkbox must be selected. This message is hidden to begin with and whenever the private form is submitted, if no one selects the checkbox, this message is displayed. Tailwind CSS is used for styling and jQuery is used for form validation and interaction.
jQuery Validation Code
Validation can be implemented using the push function of the array.
<script>
$(document).ready(function () {
$('#submit-button').on('click', function (e) {
e.preventDefault();
let language_arr = [];
$('input[name="languages[]"]:checked').each(function () {
language_arr.push($(this).val());
});
if (language_arr.length === 0) {
$('#message').removeClass('hidden').text('Please select at least one language.').fadeIn().delay(3000).fadeOut(function () {
$(this).addClass('hidden');
return false;
});
} else {
$('#message').removeClass('hidden').addClass('bg-green-300 text-green-950').text('You select:- ' + language_arr.join(', ').toUpperCase() + ' languages.').fadeIn().delay(3000).fadeOut(function () {
$(this).addClass('hidden');
return true;
});
}
});
});
</script>
This code is a jQuery script that clicks on the submit button of any form on a web page. It works like this: Language selection check: When the user submits the form, the script checks if there is a language option tag or not.If the user does not specify a language, the message "Please select at least one language" is displayed. If the user selects at least one language, the language name is displayed in bold type such as "English, French".
Message display: When the message is displayed, it stays on the screen for a few seconds and then automatically goes silent. If there is no language selection, the message is in red color, and if there is no language selection, it is in green color.
Thus, these scripts come in handy for form validation and user feedback.
Validation Using "serializeArray"
SerializeArray is a function that returns data in an array. This is a function of jQuery. It stores each input as an object.
<script>
$(document).ready(function () {
$('#submit-button').on('click', function (e) {
e.preventDefault();
let formData = $('form').serializeArray();
let language_arr = [];
$.each(formData, function (index, field) {
if (field.name === 'languages[]' && field.value) {
language_arr.push(field.value);
}
});
if (language_arr.length === 0) {
$('#message').removeClass('hidden').text('Please select at least one language.').fadeIn().delay(3000).fadeOut(function () {
$(this).addClass('hidden');
return false;
});
} else {
$('#message').removeClass('hidden').addClass('bg-green-300 text-green-950').text('You select:- ' + language_arr.join(', ').toUpperCase() + ' languages.').fadeIn().delay(3000).fadeOut(function () {
$(this).addClass('hidden');
return true;
});
}
});
});
</script>
The job of this JavaScript code is to collect data from a form and validate it against a specific field (which is named "languages[]"). Let me explain the main thing step-by-step:
Use of jQuery: The code uses jQuery which is a popular JavaScript library. The $(document).ready() function means that the code inside it will run when the page is fully loaded.
Action on button click: When the user clicks the submit button (#submit-button), an event will be triggered that will prevent the default form submission (e.preventDefault()).
Collecting form data: formData = $('form').serializeArray(); The data of all the fields of the form is converted to an array.
Checking languages: In this code we are specifically looking at the "languages[]" field. If the user has selected a language, then the language is added to the language_array array. Meaning if a user has selected a language, then the language will be stored in language_arr.
Validation: If the user has not selected any language (i.e. language_arr.length === 0), then a message is displayed which says "Please select at least one language." This message is displayed on the screen for 3 seconds and then disappears.
Success message: If the user has selected one or more languages, then a success message is displayed which tells which languages the user has selected. This message will also be displayed for 3 seconds and then disappear.
Message style: If an error occurs (no language selected), then the message is displayed with red background and text. If languages have been selected, then the message is displayed with a green background and text.
I think this code is doing form validation in a simple and efficient way, the user is prompted for a language selection and if they select one they get a confirmation.