简体   繁体   English

即使表单永远不会被提交,也要使用html5验证?

[英]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. 我正在做的是在我的表单的提交按钮上捕获click操作, preventDefault() ,执行一些计算,然后进行ajax调用而不是提交表单。

Is there a way to use javascript to force the html5 validators to fire even if the form isn't being submitted? 有没有办法使用javascript强制html5验证器即使没有提交表单也会触发?

 $('#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. 它运行得很好,我在最新的Chrome和Firefox中测试过。 Just e.preventDefault() on the <form> : 只需<form>上的e.preventDefault()

html: HTML:

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

jQ: JQ:

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

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

Using html5 constraints the form object has some new methods. 使用html5约束,表单对象有一些新方法。 For example you can call checkValidity() on the form object to check the input. 例如,您可以在表单对象上调用checkValidity()来检查输入。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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