Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
Webforms
Categories

Why does form.submit() skip my form validation and submit handler, and how do I fix it?

You added required and type="email" to a form, and a script calls form.submit() when the user finishes. The form goes out with an empty or malformed email, and your submit listener never runs.

The cause

form.submit() is a low level method. MDN states that with it "No submit event is raised" and that "Constraint validation is not triggered." Both the validation and your submit handler are skipped by design.

The fix

Call form.requestSubmit() instead. MDN describes it as identical to activating the form's submit button: the form's content is validated, and the form is submitted only if validation succeeds. The test below uses jsdom and logs how many times the submit event fired.

const { JSDOM } = require("jsdom");

const dom = new JSDOM(`<form id="f"><input name="email" type="email" required></form>`);
const form = dom.window.document.getElementById("f");
let submits = 0;
form.addEventListener("submit", (e) => { e.preventDefault(); submits++; });

form.submit();
console.log("after submit():", submits, form.checkValidity());

form.requestSubmit();
console.log("after requestSubmit() on invalid form:", submits);

form.elements.email.value = "a@b.co";
form.requestSubmit();
console.log("after requestSubmit() on valid form:", submits);

Expected output: submit() leaves the count at 0 and the form invalid, requestSubmit() on the invalid form leaves it at 0, and requestSubmit() once the email is filled in raises it to 1. jsdom prints a "Not implemented" notice for submit() because it does not navigate. That is a jsdom limitation, not a problem with the code.

Caveats

If you validate in your own code instead, call form.checkValidity() before deciding whether to send. In the test above it returns false while the required email is empty.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode