Okay
  Public Ticket #3803719
Form Validation
Closed

Comments

  •   bigalcy started the conversation
  • [deleted] replied

    Hi,

    Such form validation is done using custom JavaScript.

    To implement conditional form validation where a field (like checkboxes) is validated only if a specific value is selected in a dropdown, you can use JavaScript to handle this logic. Here’s an example:

    <form id="conditionalForm" novalidate>
      <label for="userType">What type of user are you?</label>
      <select id="userType" name="userType" required>
        <option value="">-- Select --</option>
        <option value="painter">Painter</option>
        <option value="writer">Writer</option>
        <option value="other">Other</option>
      </select>
      
      <div id="paintTypes" style="display: none; margin-top: 10px;">
        <p>Select the types of paints you use:</p>
        <label><input type="checkbox" name="paintType" value="oil"> Oil</label>
        <label><input type="checkbox" name="paintType" value="acrylic"> Acrylic</label>
        <label><input type="checkbox" name="paintType" value="watercolor"> Watercolor</label>
        <span id="paintError" class="error" style="color: red;"></span>
      </div>
      
      <button type="submit">Submit</button>
    </form>

    JS:

    document.addEventListener('DOMContentLoaded', function () {
      const form = document.getElementById('conditionalForm');
      const userType = document.getElementById('userType');
      const paintTypes = document.getElementById('paintTypes');
      const paintCheckboxes = document.querySelectorAll('input[name="paintType"]');
      const paintError = document.getElementById('paintError');
    
      userType.addEventListener('change', function () {
        // Show or hide the paint options based on dropdown selection
        if (userType.value === 'painter') {
          paintTypes.style.display = 'block';
        } else {
          paintTypes.style.display = 'none';
          clearPaintErrors();
        }
      });
    
      form.addEventListener('submit', function (event) {
        // Clear previous errors
        clearPaintErrors();
    
        if (userType.value === 'painter') {
          // Check if at least one checkbox is selected
          const isAnyChecked = Array.from(paintCheckboxes).some(checkbox => checkbox.checked);
          if (!isAnyChecked) {
            paintError.textContent = 'Please select at least one type of paint.';
            event.preventDefault(); // Prevent form submission
          }
        }
      });
    
      function clearPaintErrors() {
        paintError.textContent = '';
      }
    });

    If a user selects “Painter” from the dropdown but doesn’t check any paint types, they will see an error.

    If any other dropdown value is selected, the paint type validation is skipped, and the form can be submitted without issue.

    Hopefully this helps.