Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect an attempted submission of invalid HTML forms?

When using HTML5 form validation, having an invalid input value in a form will halt submission of that form. How can I detect that the user attempted a failed form submission? The form's onsubmit handler does not fire when submission is halted by validation failure.

I'm currently listening for keypress and click events on the submit button to detect submit attempts. Is there a better way of detecting a failed form submission?

like image 721
wheresrhys Avatar asked Jun 25 '13 14:06

wheresrhys


People also ask

How do I show submitted data in HTML?

The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. The formtarget attribute overrides the target attribute of the <form> element. Note: The formtarget attribute is new for the <input> element with type="submit" in HTML5.

What happens when HTML form is submitted?

Most HTML forms have a submit button at the bottom of the form. Once all of the fields in the form have been filled in, the user clicks on the submit button to record the form data. The standard behaviour is to gather all of the data that were entered into the form and send it to another program to be processed.


1 Answers

A simple way to get around this is to add an event listener to each input in the form to see when it has been prevented from submitting. The 'invalid' event should do everything you need.

Example

Array.prototype.slice.call(document.querySelectorAll("[required]")).forEach(function(input){
                input.addEventListener('invalid',function(e){
                    //Your input is invalid!    
                })
            });

More info here http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/

like image 103
stwilz Avatar answered Sep 29 '22 07:09

stwilz