Here's a basic version of what I'm trying to achieve.
Since I have some awaits in the function, I use async
$(document).on('submit', '.applicationForm', async function(e) {
do some validation
if (!valid) {
return true;
}
return false;
});
But the form submits in the end.
I've even tried adding e.preventDefault() and that didn't work either.
Is this all because of the async bit?
Functions marked as async always return a Promise, so won't return false.
They also return immediately, so e.preventDefault won't work because it executes too late.
You can't wait for asyncronous code to run before cancelling the event.
Instead:
async functione.preventDefaultthe_form.submit()) if the validation passesor
Do the validation as the user interacts with the form. Set a flag to valid or invalid as they go. When the submit button is clicked, check the status of the flag.
An async function will automatically return a Promise, and since a promise that resolves to false isn't the same thing as false, the form will submit - only if exactly false is returned will the form not submit.
Always return false instead, and submit the form manually if validation passes:
$(document).on('submit', '.applicationForm', function(e) {
checkValidity(this);
return false;
});
async function checkValidity(form) {
// do some validation
if (valid) {
$(this).trigger("submit");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With