Javascript 如何在不提交表单的情况下使用 jQuery.validate?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12098103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:06:44  来源:igfitidea点击:

How can I use jQuery.validate without submitting the form?

javascriptjqueryjquery-validate

提问by Brent Lawson

I have read several of the other posts about this and still no go. Trying to keep it real simple. I need to validate sections of a form that are being hidden/shown in a jQuery accordion before final submit. I have been using jquery.validate.jsfor a long time and as long as I validate on submitall is good, but now when I try to validate on button clickit is not working.

我已经阅读了其他几篇关于这个的帖子,但仍然没有去。试图让它真正简单。我需要在最终提交之前验证在 jQuery 手风琴中隐藏/显示的表单部分。我已经使用jquery.validate.js了很长时间,只要我验证submit一切都很好,但是现在当我尝试在按钮上验证时click它不起作用。

    <script type="text/javascript">
jQuery().ready(function(){
    var demo = $(".demo").accordion({
        header: '.header',
        event: false
    });

    var nextButtons = $([]);
    $("h3.header", demo).each(function(index) {
        nextButtons = nextButtons.add($(this)
        .next()
        .children(":button")
        .filter(".next, .previous")
        .click(function() {
            demo.accordion("activate", index + ($(this).is(".next") ? 1 : -1))
        }));
    });

});
</script>
<script type="text/javascript">

$(".next").click(function(){
$("#test").validate({              
     rules: {
                     name: "required", // simple rule, converted to {required:true}
                     email: {// compound rule
                         required: true,
                         email: true
                     },
                     comment: {
                         required: true
                     }
                 },
                 message: {
                     comment: "Please enter a comment."
                 }
             });


});
</script>
    <div class="demo">
<form action="#" method="post" id="test">
  <fieldset>
<div id="accordion">
    <h3 class="header"><a href="#">Section 1</a></h3>
    <div class="sec1">
    <label for="name">Name:</label>
    <input type="text" id="name" placeholder="Enter your 
full name" class="required" />
<input type="button" class="next" value="NEXT" />
    </div>
    <h3 class="header"><a href="#">Section 2</a></h3>
    <div class="sec2">
    <label for="email">Email:</label>
    <input type="email" id="email" placeholder="Enter 
your email address" class="required" />
<input type="button" class="next" value="NEXT" />
<input type="button" class="previous" value="Previous"/>
    </div>
    <h3 class="header"><a href="#">Section 3</a></h3>
    <div class="sec3">
    <label for="message">Message:</label>
    <textarea id="message" placeholder="What's on your 
mind?" class="required"></textarea>
    <input type="submit" value="Send message" />
    <input type="button" class="previous" value="Previous"/>
    </div>
      </fieldset>
</form>

</div>
</div><!-- End demo -->

回答by Sparky

The problem is that you cannot initialize validate()insidea handler. You initialize it inside the document.readyand use .valid()to test for validity. A submit button is not required to validate the form in this case.

问题是您无法validate()处理程序中进行初始化。您在内部初始化它document.ready并用于.valid()测试有效性。在这种情况下,不需要提交按钮来验证表单。

As per this answer:

根据这个答案

.validate()is what initializes the Validation plugin on your form.

.validate()是在您的form.

.valid()returns trueor falsedepending on if your form is presently valid.

.valid()返回truefalse取决于您的表格目前是否有效。

So within your .click()handler, you'd use .valid(), not .validate(), in conjunction with an ifstatement to test if form is valid...

因此,在您的.click()处理程序中,您将使用.valid(), not.validate()结合if语句来测试表单是否有效...

$(document).ready(function() {
    $("#test").validate({  // initialize plugin on the form
         rules: {
         ...
         }
         ...
         // etc.
    });

    $(".next").click(function(){  // capture the click
        if($("#test").valid()){   // test for validity
            // do stuff if form is valid
        } else {
            // do stuff if form is not valid
        }
    });
});

See docs.jquery.com/Plugins/Validation/validfor more info.

有关更多信息,请参阅docs.jquery.com/Plugins/Validation/valid

Normally, you would have a type="submit"button within the formcontainer and, in that case, would not need to capture any clicks as this is all done automatically. This answer is tailored for the OP's specific case where a traditional submitbutton is not used.

通常,容器中会有一个type="submit"按钮form,在这种情况下,不需要捕获任何点击,因为这一切都是自动完成的。这个答案是submit为不使用传统按钮的 OP 的特定情况量身定制的。

Side-note:All of your JavaScript can be contained within a singleset of <script></script>tags. Multiple sets of tags all strung together is unnecessary and superfluous.

边注:所有你的JavaScript可以包含一个内集的<script></script>标签。多组标签串在一起是不必要的和多余的。