Using HTML5 validation…
In HTML5 browsers, validation occurs before the submit event. So if the form is invalid, the submit event never fires.
I would like to hook an event into the form submit, to fire whether the form validates or not. Here’s a small example, where I’m trying to alert() when the user submits the form.
HTML:
<!DOCTYPE html>
<html>
<head><title>Example</title></head>
<body>
<form>
<input type="text" name="foo" required title="Foo field"/>
<input type="submit"/>
</form>
</body>
</html>
JavaScript:
$(function() {
$('form').submit(function() {
alert('submit!')
});
});
Interactive demo: http://jsfiddle.net/gCBbR/
My question is: do browsers provide an alternative event that I can bind to that will run before the validation?
Yes, there is an event for that reason. The event is called
invalidwhen user tries to submit the for orr when you check validity via HTML5 validation methodcheckValidity(). This event does not fire onbluror something like that without callingcheckValidity()just because you have HTML validation attributes in yourinputtags. But it does fire on before form submit.From W3C:
For example you have this markup:
Then you need to call
checkValidity()to fireinvalidevent if theinputdata is invalid:Look at my example here: http://jsbin.com/eluwir/2