JQuery Validate: How do I add validation which checks the sum of multiple fields?

前端 未结 1 372
迷失自我
迷失自我 2021-01-14 03:30

I\'m trying to use jQuery validation for a dynamic form I\'m setting up.

In some cases this form contains a set of input boxes which are suppose to total 100.

<
相关标签:
1条回答
  • 2021-01-14 04:01
    <script>
    $(document).ready(function(){
        $("#some-form").validate({
    
            rules: {
                TextBox1: {
                    required: true,
                    number: true,
                    min: 0,
                    max: 100,
                },
                TextBox2 : {
                    required: true,
                    number: true,
                    min: 0,
                    max: 100,
                }
                TextBox3 : {
                    required: true,
                    number: true,
                    min: 0,
                    max: 100,
                }
                TextBox4 : {
                    required: true,
                    number: true,
                    min: 0,
                    max: 100,
                }
    
            },
            submitHandler: function(form){
                var total = parseInt($("#TextBox1").val()) + parseInt($("#TextBox2").val()) + parseInt($("#TextBox3").val()) + parseInt($("#TextBox4").val());
                if (total != 100) {
                    $(".error").html("Your total must sum to 100.")
                    return false;
                } else form.submit();
            }
    
        });
    });
    
    </script>
    

    Stolen and edited from here.

    0 讨论(0)
提交回复
热议问题