Checkbox Validation In JavaScript

Checkbox Validation In JavaScript

In this article, we'll discuss "Checkbox Validation In JavaScript". We'll explore the core techniques for ensuring data accuracy and improving user interaction on your website. Whether you're a beginner or an experienced developer, mastering checkbox validation is key to maintaining data integrity and providing a seamless user experience. 

Checkbox Validation In JavaScript

Table of Content

  • Create Form
  • Design CSS
  • Validation Code

Create Form


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript Validation</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header wrapper">
                            <h3 class="title">Rays Coding :- JavaScript Validation</h3>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <label class="form-label">Language</label>
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <input class="language" type="checkbox" value="hindi">
                                                    <span>Hindi</span>
                                                </div>
                                                <div class="col-lg-6">
                                                    <input class="language" type="checkbox" value="english">
                                                    <span>English</span>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-lg-6">
                                                    <input class="language" type="checkbox" value="tamil">
                                                    <span>Tamil</span>
                                                </div>
                                                <div class="col-lg-6">
                                                    <input class="language" type="checkbox" value="marathi">
                                                    <span>Marathi</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row error-row" id="errorRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-danger" id="error"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row success-row" id="successRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-success" id="success"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="field">
                                            <button type="button" class="btn btn-primary w-100" onclick="validation()">SUBMIT</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="script.js"></script>
    </body>
    </html>


The HTML code creates a simple webpage using the Bootstrap framework to style a form within a card component. The page includes a header with the title "Rays Coding :- JavaScript Validation" and a form for language selection with checkboxes for Hindi, English, Tamil, and Marathi. Additionally, the form has hidden rows for displaying error and success messages, which are controlled through JavaScript. The submit button triggers a validation() function defined in an external script.js file, which performs the necessary validation checks on the form inputs.

Checkbox Validation In JavaScript


The layout is designed using Bootstrap's grid system to ensure responsiveness and a clean structure. The form uses the .container, .row, and .col-lg-12 classes to organize the content, and the card component provides a visually appealing container for the form elements. Error and success messages are displayed in alert boxes that are initially hidden and only shown based on the validation outcome. The overall structure allows for dynamic interaction with the form, providing user feedback based on the validation logic implemented in the JavaScript file.

2. CSS Styling


    @import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
    *
    {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Poppins', sans-serif;
    }
    .card
    {
        width: 60%;
        margin: 10px auto;
    }
    .wrapper
    {
        background: #fff;
        border-radius: 15px;
        box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.1);
        background: linear-gradient(-135deg, #c850c0, #4158d0);
    }
    .title
    {
        color: #fff;
        text-shadow: 0 0 10px #fff;
        text-align: center;
    }
    .field input[type="checkbox"]
    {
        border: 1px solid #4158d0;
        border-radius: 4px;
        width: 16px;
        height: 16px;
        background-color: #ffffff;
        cursor: pointer;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        display: inline-block;
        position: relative;
    }
    .field input[type="checkbox"]:checked
    {
        background-color: #4158d0;
        border-color: #4158d0;
    }
    .field input[type="checkbox"]:checked::after
    {
        content: '';
        position: absolute;
        top: 2px;
        left: 6px;
        width: 4px;
        height: 8px;
        border: solid white;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
    }
    .field input[type="checkbox"]:hover
    {
        border-color: #1e3a8a;
    }
    .field input[type="checkbox"]:focus
    {
        outline: none;
        box-shadow: 0 0 2px 2px rgba(65, 88, 208, 0.5);
    }
    .field span
    {
        color: #4158d0;
    }
    .field button
    {
        border: none;
        outline: none;
        background: linear-gradient(-135deg, #c850c0, #4158d0);
    }
    .error-row
    {
        display: none;
    }

3. JavaScript Validation Script


    function validation()
    {
        let checkboxes = document.querySelectorAll('.language');
        let checkedLanguages = [];
        checkboxes.forEach(function(checkbox)
        {
            if (checkbox.checked)
            {
                checkedLanguages.push(checkbox.value.toUpperCase());
            }
        });
        if (checkedLanguages.length === 0)
        {
            document.getElementById('error').innerText = "Please select at least one language.";
            document.getElementById('errorRow').style.display = "block";
            hideError();
            return false;
        }
        else
        {
            document.getElementById('success').innerText = 'Selected Languages: ' + checkedLanguages.join(', ');
            document.getElementById('successRow').style.display = "block";
            return true;
        }
    }
    // Hide error message
    function hideError() {
        setTimeout(function() {
            document.getElementById('errorRow').style.display = "none";
        }, 5000);
    }


Checkbox Validation In JavaScript


Validation Function

This function is triggered when the submit button on the form is clicked. It performs validation on the language checkboxes.

1. Selecting Checkboxes:

  let checkboxes = document.querySelectorAll('.language');

This line selects all elements with the class language (which are the checkboxes for language selection).

2. Checking Checked Checkboxes:

    let checkedLanguages = [];
    checkboxes.forEach(function(checkbox)
    {
        if (checkbox.checked)
        {
            checkedLanguages.push(checkbox.value.toUpperCase());
        }
    });

This code initializes an empty array checkedLanguages. It then iterates over each checkbox using forEach. If a checkbox is checked (checkbox.checked is true), it adds the checkbox's value (converted to uppercase) to the checkedLanguages array.

3 Validation Check:

    if (checkedLanguages.length === 0)
    {
        document.getElementById('error').innerText = "Please select at least one language.";
        document.getElementById('errorRow').style.display = "block";
        hideError();
        return false;
    }

This block checks if no checkboxes are selected (checkedLanguages.length === 0). If true, it displays an error message:
  • Sets the inner text of the error element to "Please select at least one language."
  • Makes the errorRow (which contains the error message) visible by setting its display style to "block".
  • Calls the hideError() function to hide the error message after a delay.
  • Returns false to prevent form submission.


4. Success Handling:

    else
    {
        document.getElementById('success').innerText = 'Selected Languages: ' + checkedLanguages.join(', ');
        document.getElementById('successRow').style.display = "block";
        return true;
    }

If at least one checkbox is selected, it displays a success message:
  • Sets the inner text of the success element to list the selected languages, joined by commas.
  • Makes the successRow (which contains the success message) visible by setting its display style to "block".
  • Returns true, indicating that the form can be submitted successfully.
Checkbox Validation In JavaScript
hideError Function
This function hides the error message after a delay.

1. Setting a Timeout:

    function hideError() {
        setTimeout(function() {
            document.getElementById('errorRow').style.display = "none";
        }, 5000);
    }

This function uses setTimeout to execute a function after a delay of 5000 milliseconds (5 seconds). The function sets the display style of the errorRow element to "none", effectively hiding the error message.

Post a Comment

Previous Post Next Post

Recent in Technology