我有一个基于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)
})
})()
实时示例
我也遇到了同样的问题,看到了这篇非常有用的帖子。
以下代码可能会有所帮助:
......
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();
});
}
它将在表单提交后重新加载页面。
这可能为时已晚,但我希望它能帮助其他人。我也有同样的问题。然后,在提交表单之前,我尝试在SweetAlert确认框中结合引导验证。我创建如下代码:
$('#submitForm').on('click', function (e) {
e.preventDefault();// prevent form submit
/*this part is taken from bootstrap validation*/
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() === false) {
form.classList.add('was-validated');
}
else {
Swal.fire({
title: 'Are you sure?',
text: "It cannot be undone",
type: 'warning',
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, send it!'
}).then((result) => {
if (result.value) {
/*submit the form*/
$("#formsubmitsekali").submit();
}
});
}
}, false);
});
submitForm
是用于提交表单的按钮ID的ID名称。formsubmitsekali
是表单ID。
这样,如果未填写必填字段,它将显示引导程序验证,而不显示Sweetalert确认框。但如果填写了所有必填字段,则会显示Sweetalert。同样的行为也会发生,如果您有电子邮件输入类型,但它是由非电子邮件填充的,它将首先运行引导验证。如果您在输入类型中使用HTML5模式,并且用户填充了错误的模式,那么这也是可行的。