I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit
. Can we do anything other than using JavaScript validation or changing the type to submit
?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform()
.
Try this out:
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
HTML5 Validation Work Only When button type will be submit
change --
To --
Either you can change the button type to
submit
Or you can hide the submit button, keep another button with type="button" and have click event for that button
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the
submit()
method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the
checkValidity()
method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since thevalidityMessage
property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the
submit()
method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.Having a form:
This will trigger form validation:
Or without jQuery
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/