使用jQuery Validate插件验证三个文本字段

时间:2014-01-04 08:28:34

标签: jquery forms jquery-validate

我有三个文字字段,用数字填充。这三个文本字段的总数应该总是达到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是做什么的。似乎没有关于它的任何信息。

2 个答案:

答案 0 :(得分:4)

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

  

“我有三个文本字段,用数字填充。这三个文本字段的总数应该总计为100.我正在使用jQuery Validation插件......”

工作代码: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,我甚至不确定它是否是当前有效的方法。引用:“似乎没有关于它的任何信息。”〜这应该是一个红旗,它可能不是一个有效的选项或方法。在声明为true时,似乎只是说自定义规则为class,但是通过使用字段class中的任何自定义规则,您将规则声明为true 。换句话说,它要么什么都不做,要么就是多余的......只需删除它。

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

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

  • 我使用errorPlacement回调将错误消息放在一个更合理的位置,紧挨着总字段。根据需要进行调整。

  • 我没有看到你的代码有任何错误,只是缺乏实现。请参阅文档:http://jqueryvalidation.org

答案 1 :(得分:0)

http://jsfiddle.net/UR4sX/

您会注意到以下几点:

  1. if(sPerct&gt; 0&amp;&amp; lPerct&gt; 0&amp;&amp; perct&gt; 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);
    });