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

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


当前回答

我知道这个问题已经有了答案,但我还有另一个可能的解决方案。

如果使用jquery,你可以做到这一点。

首先在jquery上创建两个扩展,这样你就可以在需要时重用它们。

$.extend({
    bypassDefaultSubmit: function (formName, newSubmitMethod) {
        $('#'+formName).submit(function (event) {
            newSubmitMethod();
            event.preventDefault();
        }
    }
});

接下来,在你想使用它的地方做一些这样的事情。

<script type="text/javascript">
    /*if you want to validate the form on a submit call, 
      and you never want the form to be submitted via
      a normal submit operation, or maybe you want handle it.
    */
    $(function () {
        $.bypassDefaultSubmit('form1', submit);
    });
    function submit(){ 
        //do something, or nothing if you just want the validation
    }

</script>

其他回答

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

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

<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中)。如果其他人可以在其他浏览器上添加测试这个理论的评论,我会更新这个答案。 触发验证的东西不一定在<表单>中。这只是一种干净而灵活的通用解决方案。

在不使用提交按钮的情况下检查所有必须填写的字段,您可以使用下面的功能。

您必须为控件分配所需的属性。

  $("#btnSave").click(function () {
    $(":input[required]").each(function () {                     
        var myForm = $('#form1');
        if (!$myForm[0].checkValidity()) 
          {                
            $(myForm).submit();              
          }
        });
  });

这是让HTML5对任何表单执行验证的一种非常直接的方式,同时仍然拥有对表单的现代JS控制。唯一需要注意的是提交按钮必须在<form>内。

html

<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>

js

// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );

function newAcctSubmit()
{
  var myForm = jQuery( "#newUserForm" );

  // html 5 is doing the form validation for us,
  // so no need here (but backend will need to still for security)
  if ( ! myForm[0].checkValidity() )
  {
    // bonk! failed to validate, so return true which lets the
    // browser show native validation messages to the user
    return true;
  }

  // post form with jQuery or whatever you want to do with a valid form!
  var formVars = myForm.serialize();
  etc...
}
$(document).on("submit", false);

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

这种方法对我来说很有效:

Add onSubmit attribute in your form, don't forget to include return in the value. <form id='frm-contact' method='POST' action='' onSubmit="return contact()"> Define the function. function contact(params) { $.ajax({ url: 'sendmail.php', type: "POST", dataType: "json", timeout: 5000, data: { params:params }, success: function (data, textStatus, jqXHR) { // callback }, error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR.responseText); } }); return false; }