我在我的应用程序中有这个表单,我将通过AJAX提交它,但我想使用HTML5进行客户端验证。因此,我希望能够强制表单验证,也许通过jQuery。

我想在不提交表单的情况下触发验证。这可能吗?


当前回答

这使我能够显示带有表单验证的原生HTML 5错误消息。

<button id="btnRegister" class="btn btn-success btn btn-lg" type="submit"> Register </button>



$('#RegForm').on('submit', function () 
{

if (this.checkValidity() == false) 
{

 // if form is not valid show native error messages 

return false;

}
else
{

 // if form is valid , show please wait message and disable the button

 $("#btnRegister").html("<i class='fa fa-spinner fa-spin'></i> Please Wait...");

 $(this).find(':submit').attr('disabled', 'disabled');

}


});

注意:RegForm是表单id。

参考

希望能帮助别人。

其他回答

$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

不是最好的答案,但对我来说是可行的。

$(document).on("submit", false);

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});

这里有一种更简单的方法:

像这样创建你的表单(可以是一个什么都不做的虚拟表单):

<form class="validateDontSubmit">
...

绑定所有你不想提交的表单:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

现在让我们假设你有一个<a>(在<form>内),点击你想要验证表单:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

这里有几点注意事项:

我已经注意到,你不必实际提交表单验证发生-调用checkValidity()就足够了(至少在chrome中)。如果其他人可以在其他浏览器上添加测试这个理论的评论,我会更新这个答案。 触发验证的东西不一定在<表单>中。这只是一种干净而灵活的通用解决方案。

    if $("form")[0].checkValidity()
      $.ajax(
        url: "url"
        type: "post"
        data: {

        }
        dataType: "json"
        success: (data) ->

      )
    else
      #important
      $("form")[0].reportValidity()

来自:html5表单验证

这使我能够显示带有表单验证的原生HTML 5错误消息。

<button id="btnRegister" class="btn btn-success btn btn-lg" type="submit"> Register </button>



$('#RegForm').on('submit', function () 
{

if (this.checkValidity() == false) 
{

 // if form is not valid show native error messages 

return false;

}
else
{

 // if form is valid , show please wait message and disable the button

 $("#btnRegister").html("<i class='fa fa-spinner fa-spin'></i> Please Wait...");

 $(this).find(':submit').attr('disabled', 'disabled');

}


});

注意:RegForm是表单id。

参考

希望能帮助别人。