Trigger HTML5 Form Validation on JavaScript Submission (form.submit())

Most of the time when dealing with web forms, we either have a basic version where the user clicks on the submit button and the form submits to the relevant action with the relevant GET/POST method specified (or defaults are used) or on submission of the form we use AJAX/XHR to send the form date to a specific URL with the required request type (GET, POST, PUT, UPDATE, DELETE, etc.). For a long time we had been implementing client side form validations in our JavaScript code (we still do) but then with the advent of the HTML5 constraint validation we have been doing a lot of the form validations right there in the form controls definitions by specifying the right type like email, phone, etc. with/without attributes like pattern, maxlength, required, steps, etc.

Validation on form.submit()

It’s a rare requirement I think but just incase you want to submit your form via JavaScript (not an AJAX submission/request) using form.submit(), to ensure that constraint validation kicks in, i.e., the form fields do get validated basis the attributes we specify like required or type="email", the only way to do that would be to trigger a click on the submit button after checking the validity of the form. By default, the submit() method won’t invoke form validation (I’ll explain why later). Here’s a demo to help you understand better:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

See the Pen yOOXQy by Rishabh (@rishabhp) on CodePen.

When you click on the “Submit Form via JS” hyperlink, the form gets properly validated before submission due to this piece of code:

submit_form_btn.addEventListener('click', function () {
  if (form.checkValidity()) {
    form.submit();
  }
  else {
    form.querySelector('input[type="submit"]').click();
  }
}, false);

Notice I check validity with form.checkValidity() method which if true submits the form otherwise issues a click on the submit button which is the only way to trigger form validation in code.

You’d be wondering why simply form.submit() won’t trigger the validation. Feel free to play with the demo to realise that it actually doesn’t. This is the code we’re talking about:

submit_form_btn.addEventListener('click', function () {
  form.submit();
}, false);

The reason behind that is point 4 of the form submission algorithm (in the HTML specification) that says that the constraints are validated only when the submission is not done via a submit() call programmatically. I’ve written a relevant article on point 5 of the form submission algorithm in this article that you might want to read. Again, I understand this behaviour seems weird but such is life :).

More on Constraint Validation

Apart from the checkValidity() method, there’s so much more to learn about the constraint validation module and its APIs in HTML5. Feel free to read this amazing HTML5Rocks article to learn a lot more. You’ll probably come across concepts or use cases that you wouldn’t have tried or implemented before.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

4 thoughts on “Trigger HTML5 Form Validation on JavaScript Submission (form.submit())”

  1. Theory on Gravity: Theory of gravity: I propose that when two objects are thrown in midair the velocity of the fall accelerates at a speed that is equal when it hits the ground. The two object can be as light as a pen and heavy as a ball they will fall at the same speed unless one of the object is thrown with greater force than the other then the object fall at a faster rate than the other object.

    Theory on Infinity: The theory of infinity is equal to the quorum theory of evolution. A + B squared = C. The theory of infinity is relative to the numeric system of absolute value. There is a consequence for natural order of time because of conflict and choice. In the numeric system an infinite number become absolute: 1/3, ¼, 2/3, 2/4, 3/4, 4/3, 5/3 5/4… Three are real numbers, whole numbers and rational numbers that follow a natural order in patterns that determine its relativity. A binary system is an infinite numbers that is inconclusive to matter. The theory of evolution suggest there is a natural order why we exist through the natural order of physics. Infinity determines why we exist and why we die is inconclusive in which we have no control over. The only being that surpasses life is God.

  2. Thanks this helped me solve my problem, but I think a slightly better (personal opinion) version would just hide the HTML button by using “display: none” and then whenever a custom element that is meant to submit the form is being clicked, then we cast a click event on the true, “hidden” HTML button.

    Outcome? You could remove the if clause for “checkValidity();”.

    Here is a sample:
    “`
    var real_btn = document.getElementById(“realBtn”); // this is the HTML input[type=buton]
    var fake_btn = document.getElementById(“fakeBtn”);

    fake_btn.addEventListener(‘click’, function () {
    real_btn.click();
    }, false);
    “`

  3. Thank you for every other excellent article. Where else may anyone get that type of information in such an ideal approach of writing?
    I’ve a presentation subsequent week, and I am at the look for such information.

Leave a Reply

Your email address will not be published. Required fields are marked *