Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger standard HTML5 validation (form) without using submit button?

Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).

I do not want to send POST/GET request, only do the validation.

like image 917
Mattias Wolff Avatar asked Aug 09 '11 20:08

Mattias Wolff


People also ask

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.

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.

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

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:

$(document).ready(function() {     $('#theIdOfMyForm').submit(function(event){         if(!this.checkValidity())         {             event.preventDefault();         }     }); }); 

Then just call $('#theIdOfMyForm').submit(); in your code.

UPDATE

If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function() {     if(!this.validity.valid)     {         $(this).focus();         // break         return false;     } }); 

It will give focus on the first invalid input.

like image 79
DraughtGlobe Avatar answered Oct 13 '22 05:10

DraughtGlobe


You can use reportValidity, however it has poor browser support yet. It works on Chrome, Opera and Firefox but not on IE nor Edge or Safari:

var myform = $("#my-form")[0]; if (!myform.checkValidity()) {     if (myform.reportValidity) {         myform.reportValidity();     } else {         //warn IE users somehow     } } 

(checkValidity has better support, but does not work on IE<10 neither.)

like image 21
mhm Avatar answered Oct 13 '22 06:10

mhm