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

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


当前回答

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

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

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

来自:html5表单验证

其他回答

我找到了一个适合我的方法。 只需要像这样调用一个javascript函数:

action=“javascript:myFunction();”

然后是html5验证……真的很简单:-)

我认为这是最好的方法

将使用jQuery验证插件,使用最佳实践的表单验证,它也有良好的浏览器支持。因此,您不必担心浏览器兼容性问题。

并且我们可以使用jQuery验证valid()函数来检查所选表单是否有效,或者是否所有所选元素都有效,而无需提交表单。

<form id="myform">
   <input type="text" name="name" required>
   <br>
   <button type="button">Validate!</button>
</form>
<script>
  var form = $( "#myform" );
  form.validate();
  $( "button" ).click(function() {
    console.log( "Valid: " + form.valid() );
  });
</script>
$(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; }

要检查某个字段是否有效,请使用:

$('#myField')[0].checkValidity(); // returns true|false

要检查表单是否有效,请使用:

$('#myForm')[0].checkValidity(); // returns true|false

如果你想显示某些浏览器(如Chrome)的原生错误消息,不幸的是,唯一的方法是通过提交表单,就像这样:

var $myForm = $('#myForm');

if (!$myForm[0].checkValidity()) {
    // If the form is invalid, submit it. The form won't actually submit;
    // this will just cause the browser to display the native HTML5 error messages.
    $myForm.find(':submit').click();
}

请记住,到目前为止,并不是所有浏览器都支持HTML5验证。