简体   繁体   中英

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');
    });

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/

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM