Run HTML5 form validation

I have a form with several different fields. I have Javascript that displays field sets for users one at a time. For browsers that support HTML5 validation, I would love to use it. However, I need to do this on my terms. I am using jQuery.

When the user clicks on the JS link to go to the next set of fields, I need the check to be performed in the current set of fields and block the user from moving forward if there are problems.

Ideally, when a user loses focus on an element, validation will be performed.

Currently, there is an innovation and use of Javascript. Prefers to use its own method. :)

+74
javascript jquery html5 validation
Sep 25 2018-11-21T00:
source share
10 answers

You cannot initiate your own authentication user interface, but you can easily use the verification API on arbitrary input elements:

$('input').blur(function(event) { event.target.checkValidity(); }).bind('invalid', function(event) { setTimeout(function() { $(event.target).focus();}, 50); }); 

The first event fires checkValidity for each input element, as soon as it loses focus, if the element is invalid , then the corresponding event will be fired and captured by the second event handler. This brings the focus back to the element, but it can be pretty annoying, I suppose you have a better solution for error notification. Here is a working example of my code above .

+50
Sep 26 '11 at 11:16
source share

TL; DR: Doesn't care about old browsers? Use form.reportValidity() .

Need support for older browsers? Continue reading.




In fact, you can run the scan manually.

I will use simple JavaScript in my answer to improve the reusability, jQuery is not required.




Accept the following HTML form:

 <form> <input required> <button type="button">Trigger validation</button> </form> 

And let's grab our user interface elements in JavaScript:

 var form = document.querySelector('form') var triggerButton = document.querySelector('button') 



Don't need support for legacy browsers like Internet Explorer? This is for you.

All modern browsers support the reportValidity() method for form elements.

 triggerButton.onclick = function () { form.reportValidity() } 

That is all we are done. Also, here is a simple CodePen using this approach.




An approach for older browsers

The following is a detailed explanation of how reportValidity() can be emulated in older browsers.

However, you do not need to copy and paste these blocks of code into your project yourself - you have ponyfill / polyfill for you.

Where reportValidity() not supported, we need to trick the browser a bit. So what will we do?

  1. Verify that the form is correct by calling form.checkValidity() . This will tell us if the form is valid, but does not show the validation interface.
  2. If the form is invalid, we create a temporary submit button and click on it. Since the form is invalid, we know that it will not actually be submitted, however it will show the user tips for verification. We will immediately remove the temporary send button so that it is never visible to the user.
  3. If the form is valid, we donโ€™t need to intervene at all and let the user continue.



In code:

 triggerButton.onclick = function () { // Form is invalid! if (!form.checkValidity()) { // Create the temporary button, click and remove it var tmpSubmit = document.createElement('button') form.appendChild(tmpSubmit) tmpSubmit.click() form.removeChild(tmpSubmit) } else { // Form is valid, let the user proceed or do whatever we need to } } 

This code will work in almost all common browsers (I successfully tested it before IE11).

Here is a working example of CodePen.

+72
Jan 15 '18 at 16:29
source share

To some extent, you can trigger HTML5 to validate the form and show hints to the user without submitting the form!

Two buttons, one for confirmation, one for sending

Set a onclick listener for the confirmation button to set a global flag (say justValidate ) to indicate that this click is intended to validate form validation.

And set the onclick listener to the submit button to set the justValidate flag to false.

Then, in the onsubmit handler of the form, you check the justValidate flag to resolve the return value, and call preventDefault() to stop the form from preventDefault() . As you know, HTML5 form validation (and the GUI hint for the user) is pre-generated before the onsubmit event, and even if the form is VALID, you can stop submitting the form by returning false or invoke preventDefault() .

And in HTML5, you have a form validation validation method: form.checkValidity() , and then you can see if the form is validated in the code.

OK, here is a demo: http://jsbin.com/buvuku/2/edit

+20
Dec 26 '14 at 3:45
source share

I'm not sure if you should print all of this from scratch, as this article published in List Apart explains this pretty well. MDN also has a handy tutorial on HTML5 forms and validation (covering the API as well as the corresponding CSS).

+3
Sep 25 2018-11-21T00:
source share

It is somewhat easier to add or remove HTML5 validation in fields.

  $('form').each(function(){ // CLEAR OUT ALL THE HTML5 REQUIRED ATTRS $(this).find('.required').attr('required', false); // ADD THEM BACK TO THE CURRENT FIELDSET // I'M JUST USING A CLASS TO IDENTIFY REQUIRED FIELDS $(this).find('fieldset.current .required').attr('required', true); $(this).submit(function(){ var current = $(this).find('fieldset.current') var next = $(current).next() // MOVE THE CURRENT MARKER $(current).removeClass('current'); $(next).addClass('current'); // ADD THE REQUIRED TAGS TO THE NEXT PART // NO NEED TO REMOVE THE OLD ONES // SINCE THEY SHOULD BE FILLED OUT CORRECTLY $(next).find('.required').attr('required', true); }); }); 
+3
Apr 17 '13 at 22:23
source share

I seem to have found a trick: just remove the target attribute of the form, then use the submit button to validate the form and show hints, validate the form using JavaScript, and then post anything. The following code works for me:

 <form> <input name="foo" required> <button id="submit">Submit</button> </form> 



 <script> $('#submit').click( function(e){ var isValid = true; $('form input').map(function() { isValid &= this.validity['valid'] ; }) ; if (isValid) { console.log('valid!'); // post something.. } else console.log('not valid!'); }); </script> 
+1
Sep 25 '16 at 16:22
source share

HTML code:

 <form class="validateDontSubmit"> .... <button style="dislay:none">submit</button> </form> <button class="outside"></button> 

JavaScript (using jquery):

 <script type="text/javascript"> $(document).on('submit','.validateDontSubmit',function (e) { //prevent the form from doing a submit e.preventDefault(); return false; }) $(document).ready(function(){ // using button outside trigger click $('.outside').click(function() { $('.validateDontSubmit button').trigger('click'); }); }); </script> 

Hope this helps you

+1
Dec 20 '18 at 9:13
source share

 var field = $("#field") field.keyup(function(ev){ if(field[0].value.length < 10) { field[0].setCustomValidity("characters less than 10") }else if (field[0].value.length === 10) { field[0].setCustomValidity("characters equal to 10") }else if (field[0].value.length > 10 && field[0].value.length < 20) { field[0].setCustomValidity("characters greater than 10 and less than 20") }else if(field[0].validity.typeMismatch) { field[0].setCustomValidity("wrong email message") }else { field[0].setCustomValidity("") // no more errors } field[0].reportValidity() }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="email" id="field"> 
0
Mar 01 '19 at 11:53 on
source share

If there is a very complex (especially asynchronous) verification process, there is a simple way:

 <form id="form1"> <input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" /> <input type="submit" id="form1_submit_hidden" style="display:none" /> </form> ... <script> function submitIfVeryComplexValidationIsOk() { var form1 = document.forms['form1'] if (!form1.checkValidity()) { $("#form1_submit_hidden").click() return } if (checkForVeryComplexValidation() === 'Ok') { form1.submit() } else { alert('form is invalid') } } </script> 
-one
Jan 10 '17 at 10:53 on
source share

Another way to solve this problem:

 $('input').oninvalid(function (event, errorMessage) { event.target.focus(); }); 
-2
Dec 09 '15 at 16:20
source share



All Articles