How to force a html5 form validation without submi

2019-01-01 05:00发布

I have this form in my app and I will submit it via AJAX, but I want to use HTML5 for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

I want to trigger the validation without submitting the form. Is it possible?

20条回答
素衣白纱
2楼-- · 2019-01-01 05:34

This worked form me to display the native HTML 5 error messages with form validation.

<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');

}


});

Note: RegForm is the form id.

Reference

Hope helps someone.

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 05:35

May be late to the party but yet somehow I found this question while trying to solve similar problem. As no code from this page worked for me, meanwhile I came up with solution that works as specified.

Problem is when your <form> DOM contain single <button> element, once fired, that <button> will automatically sumbit form. If you play with AJAX, You probably need to prevent default action. But there is a catch: If you just do so, You will also prevent basic HTML5 validation. Therefore, it is good call to prevent defaults on that button only if the form is valid. Otherwise, HTML5 validation will protect You from submitting. jQuery checkValidity() will help with this:

jQuery:

$(document).ready(function() {
  $('#buttonID').on('click', function(event) {
    var isvalidate = $("#formID")[0].checkValidity();
    if (isvalidate) {
      event.preventDefault();
      // HERE YOU CAN PUT YOUR AJAX CALL
    }
  });
});

Code described above will allow You to use basic HTML5 validation (with type and pattern matching) WITHOUT submitting form.

查看更多
登录 后发表回答