HTML5 validation when the input type is not "submit"

I'm nidhin picture I'm nidhin · May 23, 2013 · Viewed 141.3k times · Source

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

Answer

Jukka K. Korpela picture Jukka K. Korpela · May 23, 2013

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);
  }
}