Is there a way to intercept form submission that was triggered by JavaScript?
I'm attempting to reduce form spam submissions from bots by performing some client-side validation (with the help of reCAPTCHA v2 if it matters). When a user submits the form, I'm able to confirm that the input data has been validated (the reCAPTCHA has been filled out) by checking a flag in a method designated via the form's onSubmit attribute...
<form ... id="my_form" onSubmit="submitHandler()">
function submitHandler(e) {
if ( !valid ) {
e.preventDefault();
}
}
...or in a method defined via a jQuery .submit() event handler:
$('#my_form').submit(function(e) {
if ( !valid ) {
e.preventDefault();
}
});
The issue is that neither of these methods appear to get called when the form is submitted via JavaScript. When I open the console and test out submitting via JavaScript...
document.getElementById('my_form').submit()
...the form submits and neither method gets called. The form submit event doesn't appear to be fired, and thus I am unable to check if the data has been validated.
Presumably, this JavaScript-based form submission is the method spambots would be using to submit the form - which tracks with the fact that form spam has not been reduced via these efforts. They're able to bypass my checks.
To be clear, a third-party form service does the heavy lifting on actual field validation server-side. I'm simply trying to reduce the amount of spam that gets sent to their server in the first place.
Is it possible to intercept this JavaScript-based form submission? Am I approaching this the wrong way?
EDIT: To clarify, the onsubmit method does get called when the form is submitted via the form's submit button. But it doesn't get called when the form is submitted via JavaScript (.submit()).