JSFiddle - React, Tailwind, and code Playground

by Shree Khanal

HTML

<!doctype html>
<html lang="en">

  <head>
    <title>Validation Demo</title>
  </head>

  <body>
    <form action="" method="post">
      <table>
        <tbody>
          <tr>
            <td>Acceptable Colours:</td>
            <td class="formtable_datahelp">
              <div class="checkbox required">
                <div class="options">
                  <label class="customcheckbox">Red&nbsp;<input name="data[colour][]" type="checkbox" value="Red" /></label><br />
                  <label class="customcheckbox">Green&nbsp;<input name="data[colour][]" type="checkbox" value="Green" /></label><br />
                  <label class="customcheckbox">Blue&nbsp;<input name="data[colour][]" type="checkbox" value="Blue" /></label><br />
                  <label class="customcheckbox">White&nbsp;<input name="data[colour][]" type="checkbox" value="White" /></label><br />
                </div>
              </div>
            </td>
            <td class="formtable_help helptext">*required</td>
          </tr>
        </tbody>
      </table>
      <button type="submit">Save information</button>
    </form>
  </body>

</html>

JavaScript

$(document).ready(function () {
        const requiredElements = $('div.required  input[type=checkbox]');
        if($('div.checkbox.required :checkbox:checked').length < 0)
             this.setCustomValidity("Please select at least one option to proceed.");
        
        requiredElements.on('change', function () {
        const name = $(this).attr("name");
            $('input[name="' + name + '"]').prop('required', $('input[name="' + name + '"]:checked').length === 0);
        });
       requiredElements.trigger('change');
    });