You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Bootstrap 5.0表单验证脚本以排除隐藏字段?

How to Exclude Hidden Fields from Bootstrap 5 Form Validation

Hey there! I totally get why you'd want to skip hidden fields during Bootstrap 5 form validation—those hidden inputs shouldn't block form submission when users can't even interact with them. Let's fix that script up.

The Problem with the Original Code

The default form.checkValidity() method checks every single form control in your form, including hidden ones (like type="hidden" inputs, elements with display: none, or Bootstrap's d-none class). That's exactly what you're trying to avoid.

Modified Script to Exclude Hidden Fields

Here's the adjusted code that only validates visible form elements:

(function () {
  'use strict'

  // Grab all forms needing Bootstrap validation styles
  var forms = document.querySelectorAll('.needs-validation')

  // Loop through each form and hook up the submit handler
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        // Get all validatable form elements (inputs, selects, textareas)
        const validatableElements = form.querySelectorAll('input, select, textarea');
        let isFormValid = true;

        // Check each element, but skip hidden ones
        validatableElements.forEach(element => {
          // Check if the element is visible AND not a native hidden input
          // `offsetParent !== null` covers most hidden cases (display:none, parent hidden, etc.)
          const isVisible = element.offsetParent !== null;
          const isNotHiddenInput = element.type !== 'hidden';

          if (isVisible && isNotHiddenInput) {
            // Validate the visible element
            if (!element.checkValidity()) {
              isFormValid = false;
              // Add Bootstrap's invalid style
              element.classList.add('is-invalid');
            } else {
              // Swap to valid style if it passes
              element.classList.remove('is-invalid');
              element.classList.add('is-valid');
            }
          } else {
            // Clear validation styles for hidden elements
            element.classList.remove('is-invalid', 'is-valid');
          }
        });

        // Block submission if any visible element is invalid
        if (!isFormValid) {
          event.preventDefault();
          event.stopPropagation();
        }

        // Add Bootstrap's validated state class to the form
        form.classList.add('was-validated');
      }, false)
    })
})()

Key Changes Explained

  • Ditched form.checkValidity(): Instead of validating the whole form at once, we check each element individually to control which ones get validated.
  • Visibility Check:
    • element.offsetParent !== null is a reliable way to detect if an element is actually rendered visible on the page (covers elements hidden via display: none, parent containers hidden, etc.).
    • We also exclude type="hidden" inputs explicitly to cover native hidden fields.
  • Manual Validation Styling: We manually add/remove Bootstrap's is-valid and is-invalid classes to keep the visual feedback consistent with Bootstrap's default behavior.
  • Clear Styles for Hidden Fields: Hidden elements get their validation styles cleared so they don't interfere with the form's overall state.

Customization Option

If you only need to exclude elements using Bootstrap's d-none class (instead of all hidden elements), you can swap the visibility check to this:

const isVisible = !element.classList.contains('d-none');

This way, only elements marked with Bootstrap's official hidden class are skipped during validation.

内容的提问来源于stack exchange,提问作者Ranjeet singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:07:29