Laravel登录页:先验证BootstrapValidator再触发登录加载效果
Got it, let's fix this so your login button only switches to the loading state and submits the form after BootstrapValidator has fully validated all your inputs. Your current code runs immediately on click, skipping the validation step—here are two solid approaches to adjust that:
方案1:监听BootstrapValidator的验证成功事件
This is the most straightforward way, since it leverages BootstrapValidator's built-in event that fires only when all fields pass validation.
First, make sure your form is initialized with BootstrapValidator (add your actual validation rules here), then hook into the success.form.bv event:
// 初始化BootstrapValidator(针对id为authentication的表单) $("#authentication").bootstrapValidator({ fields: { // 示例验证规则,替换成你实际的字段和规则 email: { validators: { notEmpty: { message: "Email is required" }, emailAddress: { message: "Please enter a valid email" } } }, password: { validators: { notEmpty: { message: "Password is required" } } } } }) // 监听验证成功的事件 .on('success.form.bv', function(e) { // 阻止默认表单提交,我们要手动处理 e.preventDefault(); const $form = $(e.target); const $submitBtn = $("#loginSubmit"); // 更新按钮内容并禁用 $("#button_login_content").replaceWith("You're being logged in <i class=\"fas fa-spinner fa-spin\"></i>"); $submitBtn.prop("disabled", true); // 手动提交表单 $form.submit(); });
方案2:在按钮点击时手动触发验证
If you prefer to keep the click handler on the button, you can manually trigger validation and check if it passed before proceeding:
$("#loginSubmit").click(function(e) { // 先阻止默认的表单提交行为 e.preventDefault(); const $form = $("#authentication"); const validator = $form.data('bootstrapValidator'); // 手动触发所有字段的验证 validator.validate(); // 如果所有验证都通过 if (validator.isValid()) { // 更新按钮状态和内容 $("#button_login_content").replaceWith("You're being logged in <i class=\"fas fa-spinner fa-spin\"></i>"); $(this).prop("disabled", true); // 提交表单 $form.submit(); } });
关键注意事项
- Make sure your BootstrapValidator is properly initialized with all the validation rules you need for your login fields (email, password, etc.).
- Double-check that the
#button_login_contentelement exists inside your submit button—your original code assumes this element is there to replace the text, so your button should look something like this:<button id="loginSubmit" type="submit"> <span id="button_login_content">Login</span> </button>
内容的提问来源于stack exchange,提问作者Johnny

