Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch submit before HTML5 validation

Tags:

Is there any way to catch a form's submit action before HTML5 validation steps in?

This is what I have tried:

HTML

<form method='post' >
    <fieldset>
        <input type='email' name='foo' required />
        <input type='submit' />
    </fieldset>
</form>

jQuery

$('form').submit(function() {
    $('fieldset').addStyle('error');
    return false;
})

But the submit is only triggered once the HTML5 validation passes.

like image 502
Muleskinner Avatar asked Feb 28 '13 14:02

Muleskinner


2 Answers

Nope, the HTML5 validation happens before any submit event, in all browsers, so it's not possible, other than changing the event type, like a click on the button :

$('input[type="submit"]').on('click', function() {
    $('fieldset').addClass('error');
});

FIDDLE

like image 173
adeneo Avatar answered Oct 14 '22 19:10

adeneo


Use jquery to disable the validation on the form when the page first loads so you can prevent any validation from occurring before your onsubmit handler has run:

$(document).ready(function(){
   $('form').attr('novalidate','novalidate');
})

and then at the end of your onsubmit function, manually run the HTML5 validation on each of the fields via javascript (using checkValidity())

like image 33
Ben D Avatar answered Oct 14 '22 20:10

Ben D