引导表单输入:防止提交,但允许输入检查

Bootstrap form input: prevent submit, but allow for input checking

本文关键字:输入 许输入 检查 提交 表单      更新时间:2023-09-26

我有以下问题:我使用bootstrap表单来接收用户的输入,并使用jQuery preventDefault()来禁用提交按钮发送表单(我使用AJAX代替)。然而,该函数也阻止了由bootstrap完成的输入检查。例如,如果有人在

中输入一封没有"@"的电子邮件
<input type="email" class="form-control">

bootstrap将在单击提交时检查该输入并返回一个带有错误的弹出框。

我的问题是:如何防止请求被发送,同时保持引导表单检查机制完好无损?

我尝试过的:使用preventDefault()并编写自己的检查脚本,但是这似乎是重新发明轮子,并且在不需要的时候有额外的代码。

谢谢!

我相信你说的是原生HTML5表单验证,而不是自引导验证,我以前从未遇到过自引导验证。(虽然我可能错了)。

大多数新浏览器将验证<input type='email'/>作为电子邮件地址,<input type='text' required='required'/>作为表单提交所需的。

例如,如果你在提交按钮的点击事件上使用e.preventDefault();,表单将永远不会尝试提交,因此本机验证将永远不会发生。

如果您想保持验证,您需要在表单的提交事件上使用e.preventDefault();,而不是按钮上的单击事件。

html…

<form action='' method='post'>
   <input type='email' name='email' required='required' placeholder='email'/>
   <button type='submit'>Submit</button>
</form>

jQuery…

//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
    e.preventDefault();
    //ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
    e.preventDefault();
    //ajax code here
});

无论如何,希望这有助于。如果我有任何误解,请告诉我,我会尽力进一步协助。

我有同样的问题,我开始使用"stopPropagation"作为停止表单提交的方式。但是在阅读了jQuery 3之后,我意识到"preventDefault"已经足够满足我的需求了。

这导致表单验证发生,而提交事件没有继续。

(这个例子是我自己尝试过的)。

$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 && 
$('#id_inputBox_password').val().length == 0 ) {
    event.preventDefault();
    $('#id_inputBox_username').tooltip('show');
    $('#id_inputBox_password').tooltip('show');         
} else if ( $('#id_inputBox_username').val().length == 0 ) {
    event.stopPropagation();
    $('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
    event.stopPropagation();
    $('#id_inputBox_password').tooltip('show'); 
}
});

我有同样的问题,我找到了这个解决方案:

$('#formulario').on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    // handle the invalid form...
  } else {
    // everything looks good!
    e.preventDefault(); //prevent submit
            $(".imprimir").show();
            $(".informacao").fadeOut();
            carregardados();
  }
})