首页 > 解决方案 > 在 jQuery 中引导表单验证而不是纯 JavaScript?

问题描述

我在 Bootstrap 上找到了这个来使用 Bootstrap 表单验证。当其余的 Bootstrap 脚本都在 jQuery 中时,为什么示例使用纯 JavaScript 而不是 jQuery?

这怎么能用 jQuery 来完成?

https://getbootstrap.com/docs/4.0/components/forms/#validation

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

标签: javascriptjquerytwitter-bootstrapbootstrap-4

解决方案


$(document).ready(function(){

    $('.needs-validation').on('submit', function(e) {
      if (!this.checkValidity()) {
        e.preventDefault();
        e.stopPropagation();
      }

      $(this).addClass('was-validated');
    });

});

推荐阅读