Building on @Titulus' code above, here's how I would do it in jQuery; you can adapt this to native events if need be.
$('form-selector').on('submit', function(event) {
// Don't do anything if constraint validation isn't supported by the browser.
if (
!('checkValidity' in this) ||
// In the unlikely case this is a property but not actually a function.
// Hypothetically, a botched polyfill could do this; it pays to be careful
// and build resilient code.
typeof this.checkValidity !== 'function'
) {
return;
}
if (this.checkValidity() === true) {
// Valid values code.
} else {
// Invalid values code.
// Leave this until the last possible moment in the handler in case there's
// an error in any of the handler code to reduce the chances of a broken
// form where the submit does nothing. If an exception is thrown before
// this, the browser shouldn't get this far, (hopefully) allowing the basic
// form to still work.
event.preventDefault();
}
});
// Tell the browser to not validate automatically, as that would prevent submit
// from being triggered. We prevent the submission above if form doesn't pass
// validation. This is here in case there's an error in the preceding code, so
// this (hopefully) doesn't get applied in that case and browser validation
// takes place as a fallback.
this.noValidate = true;
oninvalid
is pretty close to what the OP is looking for. It seems thatoninvalid
only applies to inputs, rather than the form itself, though. Certainly you could put anoninvalid
handler on every input -- that seems like a valid (although somewhat brittle) solution. – ConstipateThe validity property... is defined only per input.
" I completely agree, as I said above ("...oninvalid only applies to inputs, rather than the form"). I meant that you could use a handler function as theoninvalid
listener on every validated input of the form. Thus, if there are any invalid fields, the handler will be called at least once. This is obviously brittle and suboptimal (as I said above), since you must remember to add the handler to each input. It might be possible to use event delegation to catch allinvalid
events that fire from inputs inside of a form. – Constipateoninvalid
event on the form is exactly what's needed (or, even better, perhaps anonsubmitattempt
). Maybe it'll creep into the html spec at some point. It seems like a clumsy omission for there not to be an event fired at this crucial point in a HTML5 form's flow – Goldfinchtest
function does is replicate whatform.checkValidity
already does natively – Goldfinch