【问题标题】:Validating three text fields with jQuery Validate plugin使用 jQuery Validate 插件验证三个文本字段
【发布时间】:2014-01-04 08:28:33
【问题描述】:

我有三个要填写数字的文本字段。这三个文本字段的总和应始终为 100。我使用 jQuery Validation 插件来简化事情,并使用.addmethod() 来验证这个案例。

我试过的:http://jsfiddle.net/NcW9V/

-- 下面发布的代码是 jsfiddle 中的内容的副本-- 我的 jQuery 代码:

//show the percentage
        $("#airPercent, #seaPercent, #landPercent").change(function(){
            var sPerct = $('#seaPercent').val();
            var lPerct = $('#landPercent').val();
            var perct = $('#airPercent').val();
            var newTotal = parseInt(perct) + parseInt(lPerct) + parseInt(sPerct);
            $("#totalP").empty();
            $("#totalP").text(newTotal);
        });

//the validator     
jQuery.validator.addMethod("checkModePerct", function(value) {
        total = parseInt($('#airPercent').val()) + parseInt($('#seaPercent').val()) + parseInt($('#landPercent').val());
        return total == 100;
        }, "Please only enter a sum total of 100%");

$("#contact-form").validate(
    {
    });

HTML 标记:

<form action="lane" method="post" id="contact-form" class="form-horizontal">

        <legend>Mode of Transportation:</legend>
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Air</th>
                            <th>Sea</th>
                            <th>Land</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Percentage</td>
                            <td class="span3">
                                <input type="text" class="span1" name="airPercent" id="airPercent" value="0" class="required  checkModePerct"/>%
                            </td>
                            <td class="span3">
                                <input type="text" class="span1" name="seaPercent" id="seaPercent" value="0" class="required  checkModePerct"/>%
                            </td>
                            <td class="span3">                          
                                <input type="text" class="span1" name="landPercent" id="landPercent" value="0" class="required  checkModePerct"/>%      
                            </td>
                            <td class="span3">
                                <div id="totalP">
                                    0
                                </div>%
                            </td>
                        </tr>
                    </tbody>
         </table>
        <input type="submit" value="submit"/>
</form>

我已经查看了许多其他示例,但我能找到的最接近的示例是 http://jsfiddle.net/wtmv3/。我玩过代码,但无法让它工作,因为我不确定jQuery.validator.classRuleSettings.checkTotal 做了什么。似乎也没有任何关于它的信息。

【问题讨论】:

    标签: jquery forms jquery-validate


    【解决方案1】:

    您发布了三个不同版本的代码,一个在 OP 中,两个在 jsFiddles 中。我选择了最接近你描述的那个......

    “我有三个文本字段要填写数字。这三个文本字段的总和应始终为 100。我正在使用 jQuery 验证插件...”

    工作代码:http://jsfiddle.net/K3S5S/

    $(document).ready(function () {
    
        //percentage  // I made no changes to your '.change()' handler
        $("#airPercent, #seaPercent, #landPercent").change(function () {
            var sPerct = $('#seaPercent').val();
            var lPerct = $('#landPercent').val();
            var perct = $('#airPercent').val();
            var newTotal = parseInt(perct) + parseInt(lPerct) + parseInt(sPerct);
            $("#totalP").empty();
            $("#totalP").text(newTotal);
        });
    
        jQuery.validator.addMethod("checkTotal", function (value) {
            // if you need to check total of three fields, then add up all three!
            total = parseFloat($('#airPercent').val()) + parseFloat($('#seaPercent').val()) + parseFloat($('#landPercent').val());
            return total == 100;  // returns true/false if total is 100 or not
        }, "Total must add up to 100%!");
    
        $("#contact-form").validate({
            rules: {  // declare your rule based on field "name"
                airPercent: {
                    required: true,
                    checkTotal: true
                },
                seaPercent: {
                    required: true,
                    checkTotal: true
                },
                landPercent: {
                    required: true,
                    checkTotal: true
                }
            },
            groups: {  // combine all three messages into one
                percent: "airPercent seaPercent landPercent"
            },
            errorPlacement: function (error, element) {
                 // place the message after the total
                 error.insertAfter(  $('#totalP') );  
            }
        });
    
    });
    
    • 您不需要classRuleSettings,我什至不确定它当前是否是有效方法。引用:“似乎也没有任何关于它的信息。” ~ 这应该是一个危险信号,它可能不是一个有效的选项或方法。当声明为class 时,似乎只是简单地说自定义规则为true,但是通过在字段class 中使用任何自定义规则,您将规则声明为true。换句话说,它要么什么都不做,要么是多余的......删除它。

    • 您必须在所有三个字段中声明您的自定义规则checkTotal。我已经在.validate() 方法中声明了所有规则。如果需要,您可以将它们移动到字段类中......任何一种方式都是有效的。

    • 我使用groups 选项将所有错误消息合并为一个。

    • 我使用errorPlacement 回调将错误消息放置在更合乎逻辑的位置,就在总计字段旁边。根据需要进行调整。

    • 我没有在您的代码中看到任何错误,只是缺少实现。参考文档:http://jqueryvalidation.org

    【讨论】:

    • 谢谢。当我阅读了很多教程并且其中许多都有不同的实现时,我感到很困惑。担心在每个字段的规则中添加 checkTotal: true 只会导致它被孤立地执行。
    【解决方案2】:

    http://jsfiddle.net/UR4sX/

    你会注意到几件事:

    1. if(sPerct > 0 && lPerct > 0 && perct > 0){ - 这样验证只会在所有 3 个框都填满时触发 - 否则会很烦人

    2. if(newtotal !== 100) 部分 - 目前它只显示通过或失败 - 如果在此处无效,您需要添加代码以阻止它触发。

          $("#airPercent, #seaPercent, #landPercent").change(function(){
          var sPerct = $('#seaPercent').val();
          var lPerct = $('#landPercent').val();
          var perct = $('#airPercent').val();
      
          var newTotal = parseInt(perct) + parseInt(lPerct) + parseInt(sPerct);
      
          if(sPerct > 0 && lPerct  > 0 && perct > 0){
              if (newTotal !== 100){
                  $('#valid').html("Please enter amounts totalling 100");
              }else{
                  $('#valid').html("pass");
              }
      
      
          }
      
      
          $("#totalP").empty();
          $("#totalP").text(newTotal);
      });
      

    【讨论】:

    • 这是唯一已经工作的部分。 OP 想知道如何实现 jQuery Validate 插件,而不是如何手动验证它。
    • 实际上,OP 说他们添加了 jQuery 验证器是为了方便 - 但没有具体说他们想使用它 - 我的答案可以完成这项工作,而且开销比 jQuery validate 少 - 世界没有不要在你知道的插件上运行! :-D
    • Quote: “这个世界不是在你知道的插件上运行的!” ~ 很讽刺你提到使用插件的开销,而你的答案却不必要地依赖于 jQuery简单的 JS 任务......一个“插件”本身。
    • 没有开始谩骂比赛 - 他已经在使用 jQuery - jQuery 验证器使用比我的答案更多的处理能力 - 很简单 - 我赞成你的答案 - 冷静下来,我们是来帮助其他人的相信每个人都会选择我们的答案!
    • 我可以同时回答这两个问题 - getelementbyID 与 $('#val) 相比开销最小 - 关键点(Sparky 错过了)是使用内置的 jQuery 函数手动检查值减少了-head 作为 jQuery 验证器效率不高。 Sparkys 的答案对可维护性更好我只是展示了如何手动验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多