[Drupal] How to add Javascript validation to a checkbox to a Drupal form?

| | 1 min read

Suppose you have a checkbox in a Drupal webform that needs to be validated before submitting the form. You may be familiar with Drupal form validation but you can add validation using Javascript too. If you have a Drupal form in your Drupal website and want to know how to add Javascript validation to a checkbox to a Drupal form then read on

Follow the steps below to add JS validation to your Drupal forms

Steps

  • Lets look at an example form as shown by the HTML below.
    <div class="proof-approval"> 
      <input type="checkbox" name="approval"/>I Approve</input>
    </div>
  • This is the checkbox that I have to validate. To do so, I am going to add the following code to the JS file in my Drupal site.
    $('#edit-submit').click(function() {
      var count = $("input[name*='approval']:checked").length;
      if(count==0) {
        alert('Please Select the Approval box .');
        $('.proof-approval').css("border","2px solid red");
        return false;
      }
      else
       return true;
    });
  • The above code does the following things
    1. When the submit button is clicked, it stores the length of the checkbox to the variable count.
    2. If the count is 0, that means the checkbox is not checked and an alert message is displayed.
    3. A red-border will also be displayed around the checkbox and the function returns FALSE.
    4. If the count is 1, that means the checkbox has been checked and the function returns TRUE.
  • Now the checkbox validation is complete.

Hope that helps. If you have any questions regading JS validation of Drupal forms use the comment form below to shoot your questions.