Razor Storm
Razor Storm

Reputation: 12336

Use html5 validations even if form is never being submitted?

What I am doing is catching the click action on my form's submit button, preventDefault()ing it, doing some computation, and then making an ajax call instead of submitting the form.

Is there a way to use javascript to force the html5 validators to fire even if the form isn't being submitted?

 $('#submitButton').click(function (e) {
        e.preventDefault(); //stop the form from submitting

        //Do computation

        $.post('/comments', values, function(results) {
            hideForm($('#new_comment_' + parentId));
            parent.children('.children').prepend(results);
        }, 'html');
    });

Upvotes: 3

Views: 2010

Answers (2)

Alex
Alex

Reputation: 2126

Using html5 constraints the form object has some new methods. For example you can call checkValidity() on the form object to check the input.

<form method="post" action="test.html" id="myForm">
    <input type="text" required></input>
    <input type="submit" value="Submit" id="submitButton">
</form>

<script type="text/javascript">
    $('#submitButton').click(function (e) {
        e.preventDefault();
        alert($("#myForm").get()[0].checkValidity());
    })
</script>

Upvotes: 3

elclanrs
elclanrs

Reputation: 94101

It works just fine, I tested in latest Chrome and Firefox. Just e.preventDefault() on the <form>:

html:

<form method="post" action="test.html">
    <input type="text" required></input>
    <input type="submit" value="Submit">
</form>

jQ:

$('form').submit(function(e){ e.preventDefault(); });

example: http://jsfiddle.net/elclanrs/2nnLc/2/

Upvotes: 8

Related Questions