DrowningInCode
DrowningInCode

Reputation: 183

Validating three text fields with jQuery Validate plugin

I have three text fields which are to be filled up with numbers. The total of these three text fields should always add up to 100. I'm using the jQuery Validation plugin to ease things and have used .addmethod() to validate this case.

What I've tried: http://jsfiddle.net/NcW9V/

--the code posted below is a copy of what is found in the jsfiddle-- My code for the 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(
    {
    });

The HTML markup:

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

I've gone through a number of other examples but the closest I can find is http://jsfiddle.net/wtmv3/. I played with the code but can't get it to work as I'm not sure what jQuery.validator.classRuleSettings.checkTotal does. There doesn't seem to be any information about it either.

Upvotes: 0

Views: 2149

Answers (2)

Sparky
Sparky

Reputation: 98738

You posted three different versions of code, one in the OP and two jsFiddles. I picked the one closest to what you described...

"I have three text fields which are to be filled up with numbers. The total of these three text fields should always add up to 100. I'm using the jQuery Validation plugin..."

Working Code: 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') );  
        }
    });

});
  • You don't need the classRuleSettings and I'm not even sure if it's currently a valid method. Quote: "There doesn't seem to be any information about it either." ~ That should be a red flag that it's likely not a valid option or method. It appears to simply say the custom rule is true when declared as a class, however by using any custom rule within a field class, you are declaring the rule as true. In other words, it's either doing nothing or it's superfluous... just remove it.

  • You must declare your custom rule checkTotal on all three fields. I have declared all rules within the .validate() method. You can move them into the field classes if you want... either way is valid.

  • I used the groups option to combine all error messages into one.

  • I used the errorPlacement callback to place the error message in a more logical location, right next to the total field. Adjust as needed.

  • I did not see any mistakes in your code, just a lack of implementation. Refer to documentation: http://jqueryvalidation.org

Upvotes: 4

GrahamTheDev
GrahamTheDev

Reputation: 24875

http://jsfiddle.net/UR4sX/

You will notice a couple of things:

  1. if(sPerct > 0 && lPerct > 0 && perct > 0){ - this is so the validation only fires when all 3 boxes are filled out - otherwise it would be annoying

  2. The if(newtotal !== 100) section - at the moment it only shows pass or fail - you would need to add code to stop it firing if not valid in here.

        $("#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);
    });
    

Upvotes: 0

Related Questions