如何使用JQuery验证插件进行条件成功检查? [英] How can I do a conditional success check with the JQuery Validation Plugin?

查看:94
本文介绍了如何使用JQuery验证插件进行条件成功检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery验证插件,但遇到一个小问题.我的表单使用以下方法来隐藏/显示所需的内容:

I am attempting to use the JQuery Validation Plugin but am running in to a small problem. My form uses the following method to hide/show the desired content:

<div id="page1" class="page" style="visibility:visible;">
...Page 1 form content...
</div>
<div id="page2" class="page">
...Page 2 form content...
</div>

表单有两页...这是第1页上的按钮,允许用户继续.

Form has two pages...here is the button on Page 1 that allows the user to Continue.

<input type="button" id="C1" value="Continue" onClick="showLayer('page2')">

showLayer()函数只是切换所传递元素的可见性.唯一需要验证的内容是此按钮所在的第1页.我要执行的操作是先单击继续"按钮,然后调用.validate(),然后在成功验证后进入第二页.研究表明,让onClick调用多个函数是一件容易的事,就像这样:

The showLayer() function simply toggles the visibility of the passed element. The only content that needs to be validated is on page 1, where this button is located. What I would like to do is have the Continue button first call .validate() and then upon successful validation proceed to the second page. Research has shown me that it is an easy thing to have the onClick call multiple functions like so:

<input type="button" id="C1" value="Continue" onClick=".validate()";"showLayer('page2')">

尽管这种技术上"有效,但用户发现自己正在查看第2页的内容,并不知道他/她将在第1页上看到验证错误,除非他们单击"Go Back"(返回)按钮.显然不是一个非常有用的情况!

While this "technically" works, the user finds himself viewing page 2 content with no clue that he/she is being presented validation errors back on page 1 unless they click the "Go Back" button. Obviously not a very usable situation!

我已经尝试过了,但是仍然面临着相同的基本问题.

I have tried this but am still faced with the same basic problem.

<input type="button" id="C1" value="Continue" onClick="formValidate()">

function formValidate() {
    .validate();
    showLayer('page2');
}

所需的是确定验证功能是否成功返回,然后假设所有验证均通过,然后有条件地继续执行第2页.在研究了插件文档之后,我发现以下是我最有可能(我认为)的候选人:

What is needed is to determine whether the validation function came back successfully and then conditionally continue on to page 2 assuming all validations pass. After research into the plugin documentation I have come across the following to be my most likely (I think) candidate to achieve this:

"invalidHandler"

    $(".selector").validate({

  invalidHandler: function(event, validator) {
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});

...但是我不知道如何将其与所需的条件检查结合在一起.我不需要如示例所示显示错误计数,但似乎可以执行正确的回调,并提供一个错误计数(我会认为)来提供成功检查的基础和框架有条件的.我很可能在错误的树上吠叫,也许有更好的方法来完成此任务...有什么想法吗?感谢所有帮助!

...but I don't know how to tie it together with the conditional checking needed. I don't need to display the error count as the example shows but it seems to do the proper callback with an error count that (I would think) provide the basis for the success check and the framework for the conditional. I may very well be barking up the wrong tree and there may be a much better way to accomplish this... Any ideas? All help much appreciated!

更新 * ** * ** * ** * ** * ** JSFiddle http://jsfiddle.net/uEh3a/ 不知道我是否正确地做到了……第一次!

UPDATE *************** JSFiddle http://jsfiddle.net/uEh3a/ Not sure if I have done this right...first time!

在我从Sparky添加代码之前,该表单会根据所选的单选按钮进行一些自动计算.代码添加后没有计算,并且不能在窗体之间移动.我确定我做了一些愚蠢的事情……有人可以看到吗?

Before I added the code from Sparky the form did some automatic calcs based on the radio buttons selected. After code added no calcs and cannot move between forms. I'm sure I've done something dumb...can anybody see what?

推荐答案

有很多方法可以做到这一点,但是下面的演示中也包含了您问题的很大一部分答案,那就是使用以编程方式测试表格的方法.您可以在下面全部或部分使用我的示例.

There are lots of ways to do this, but the demo below also contains a large part of the answer to your question, which would be to use the .valid() method to programatically test the form. You can use my example below in whole or in part.

当我创建多步骤表单时,我为每个部分使用一组唯一的<form>标签.然后,我将使用 .valid()方法测试该部分,然后再继续进行下一部分. (别忘了先初始化插件;在DOM上的所有表单上都调用.validate().)

When I create multi-step forms, I use a unique set of <form> tags for each section. Then I use the .valid() method to test the section before moving to the next. (Don't forget to first initialize the plugin; call .validate(), on all forms on DOM ready.)

然后在最后一节中,我在每种表单上使用.serialize()并将它们连接到要提交的数据查询字符串中.

Then on the last section, I use .serialize() on each form and concatenate them into a data query string to be submitted.

类似这样的事情...

Something like this...

$(document).ready(function() {  // <-- DOM ready handler

    $('#form1').validate({ // initialize form 1
        // rules
    });

    $('#gotoStep2').on('click', function() { // go to step 2
        if ($('#form1').valid()) {
            // code to reveal step 2 and hide step 1
        }
    });

    $('#form2').validate({ // initialize form 2
        // rules
    });

    $('#gotoStep3').on('click', function() { // go to step 3
        if ($('#form2').valid()) {
            // code to reveal step 3 and hide step 2
        }
    });

    $('#form3').validate({ initialize form 3
        // rules,
        submitHandler: function (form) {
           // serialize and join data for all forms
           var data = $('#form1').serialize() + '&' + $('#form2').serialize() + '&' + $(form).serialize()
           // ajax submit
           return false; // block regular form submit action
        }
    });

    // there is no third click handler since the plugin takes care of this 
    // with the built-in submitHandler callback function on the last form.

});

重要的是要记住我上面的click处理程序没有使用type="submit"按钮.这些是常规按钮,它们是form标签的外部type="button".

Important to remember that my click handlers above are not using type="submit" buttons. These are regular buttons, either outside of the form tags or type="button".

仅最后一个表单上的按钮是常规的type="submit"按钮.那是因为我仅在最后一种形式上利用了插件的内置submitHandler回调函数.

Only the button on the very last form is a regular type="submit" button. That is because I am leveraging the plugin's built-in submitHandler callback function on only the very last form.

概念验证"演示: http://jsfiddle.net/dNPFX/

"Proof of Concept" DEMO: http://jsfiddle.net/dNPFX/

另外,请参阅以供参考:

Also, see for reference:

https://stackoverflow.com/a/19546698/594235

这篇关于如何使用JQuery验证插件进行条件成功检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆