【问题标题】:Bootstrap V5 Form Validation & Sweetalert2 : Showing success message after successful submissionBootstrap V5 表单验证和 Sweetalert2:成功提交后显示成功消息
【发布时间】:2021-04-02 15:14:40
【问题描述】:

我有一个基于 Bootstrap 5 的简单表单,带有一个验证选项,如果表单字段使用 Sweatalert2 成功提交,我正在尝试显示警报消息。

这是我的代码:

HTML

    <form action="" method="POST" class="needs-validation" novalidate>
        <label for="validationCustomUsername" class="form-label">Username</label>
        <div class="input-group has-validation mb-3">
            <span class="input-group-text" id="inputGroupPrepend">@</span>
            <input type="text" class="form-control" id="validationCustomUsername" placeholder="Username *" aria-describedby="inputGroupPrepend" required />
            <div class="invalid-feedback">
                Please choose a username.
            </div>
        </div>
        <button class="btn btn-primary" type="submit">Submit form</button>
    </form>

JS

(function () {
  'use strict'

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
})()

Live Example

【问题讨论】:

    标签: javascript html validation bootstrap-5


    【解决方案1】:

    我遇到了同样的问题,遇到了这个post,这很有帮助。

    以下代码可能会有所帮助:

    ......
     form.classList.add('was-validated');
    
    
                        if (form.reportValidity()) {
                            event.preventDefault()
                            Swal.fire({
                                position: 'center',
                                icon: 'success',
                                title: 'Your application has been submitted successfully!',
                                showConfirmButton: false,
                                timer: 2500
                            }).then((result) => {
                                // Reload the Page
                                location.reload();
                            });
                        }
    

    表单提交后会重新加载页面。

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多