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

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


当前回答

我认为这是最好的方法

将使用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>

其他回答

这使我能够显示带有表单验证的原生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。

参考

希望能帮助别人。

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

submitButton.click(function(e) {
    if (form.checkValidity()) {
        form.submit();
    }
});
$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

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

下面的代码为我工作,

$("#btn").click(function () {

    if ($("#frm")[0].checkValidity())
        alert('sucess');
    else
        //Validate Form
        $("#frm")[0].reportValidity()

});

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

如果使用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>