简体   繁体   English

Bootstrap 5:仅使用经过验证的表单运行 javascript

[英]Bootstrap 5: Run javascript only with validated form

I have a form with various input fields that are validated using bootstrap 5 validation.我有一个包含各种输入字段的表单,这些字段已使用 bootstrap 5 验证进行验证。

<form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate>
[...]
</form>

According to the documentation, the following code is responsible for this:根据文档,以下代码负责:

// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
    'use strict'
  
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')
  
    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }
  
        form.classList.add('was-validated')
      }, false)
    })
  })()

Now I want to execute a javascript function on a successful form send:现在我想在成功发送表单时执行 javascript function:

$('.asset-test').on('submit', function () {
    alert('form submitted');
});

But this function is now always executed when the submit button is pressed.但是这个 function 现在总是在按下提交按钮时执行。 So even if some input fields do not have valid content yet and the bootstrap validation fails.因此,即使某些输入字段还没有有效内容并且引导程序验证失败。

I see that 'was-validated' must be added to each field.我看到必须将“已验证”添加到每个字段。 Presumably all input fields in the forms must be checked for this?大概必须为此检查 forms 中的所有输入字段? Unfortunately I lack the javasctipt knowledge for this.不幸的是,我缺乏这方面的 javasctipt 知识。 Can someone please guide me on the right path?有人可以指导我走正确的道路吗?

Execute my javascript function only if the bootstrap validation was successful.仅当引导程序验证成功时才执行我的 javascript function。

You could add an else clause after the call of checkValidity() :您可以在调用checkValidity()之后添加一个else子句:

// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
    'use strict'
  
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')
  
    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
          console.log("invalid form");
        } else {
          console.log("valid form");
          //add some code here
        }
  
        form.classList.add('was-validated')
      }, false)
    })
  })()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM