Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a html5 form validation without submitting it via jQuery

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?

like image 644
razenha Avatar asked Aug 08 '12 14:08

razenha


People also ask

How do I bypass HTML5 validations?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

How do you do automatic HTML form validation?

1. Using HTML5 built-in functionality. HTML5 provides this feature of form validation without using JavaScript. Form elements will have validation attributes added, which will enable the form validation for us automatically.

Does HTML5 have form validation?

Using built-in form validationOne of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements.


2 Answers

To check whether a certain field is valid, use:

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

To check if the form is valid, use:

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

If you want to display the native error messages that some browsers have (such as Chrome), unfortunately the only way to do that is by submitting the form, like this:

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(); } 

Keep in mind that, HTML5 validation is not supported in all browsers till now.

like image 149
Abraham Avatar answered Sep 30 '22 01:09

Abraham


below code works for me,

$("#btn").click(function () {      if ($("#frm")[0].checkValidity())         alert('sucess');     else         //Validate Form         $("#frm")[0].reportValidity()  }); 
like image 32
Boopathi.Indotnet Avatar answered Sep 30 '22 00:09

Boopathi.Indotnet