[html] HTML5 validation when the input type is not "submit"

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().

This question is related to html forms validation html5-validation

The answer is


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 the validityMessage 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:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

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:

<form>
    <input type="text" name="title" required />
    <button style="display: none;" type="submit" id="submit-button">Not Shown</button>
    <button type="button" onclick="doFancyStuff()">Submit</button>
</form>

This will trigger form validation:

function doFancyStuff() {
    $("#submit-button").click();
}

Or without jQuery

function doFancyStuff() {
    document.getElementById("submit-button").click();
}

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/


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):

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">

<script>
function submitform() {
    $('#submit_handle').click();
}
</script>

Try this out:

<script type="text/javascript">
    function test
    {
        alert("hello world");  //write your logic here like ajax
    }
</script>

<form action="javascript:test();" >
    firstName : <input type="text" name="firstName" id="firstName" required/><br/>
    lastName : <input type="text" name="lastName" id="lastName" required/><br/>
    email : <input type="email" name="email" id="email"/><br/>
    <input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

You should use form tag enclosing your inputs. And input type submit.
This works.

<form id="testform">
<input type="text" id="example" name="example"  required>
<button type="submit"  onclick="submitform()" id="save">Save</button>
</form>

Since HTML5 Validation works only with submit button you have to keep it there. You can avoid the form submission though when valid by preventing the default action by writing event handler for form.

document.getElementById('testform').onsubmit= function(e){
     e.preventDefault();
}

This will give your validation when invalid and will not submit form when valid.


2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.

The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

Updated solution snippet:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.reportValidity()) {
    f.submit();
  }
}

HTML5 Validation Work Only When button type will be submit

change --

<button type="button"  onclick="submitform()" id="save">Save</button>

To --

<button type="submit"  onclick="submitform()" id="save">Save</button>

Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">


Either you can change the button type to submit

<button type="submit"  onclick="submitform()" id="save">Save</button>

Or you can hide the submit button, keep another button with type="button" and have click event for that button

<form>
    <button style="display: none;" type="submit" >Hidden button</button>
    <button type="button" onclick="submitForm()">Submit</button>
</form>

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to html5-validation

HTML5 validation when the input type is not "submit" Is there a minlength validation attribute in HTML5?