Winns
Winns

Reputation: 902

Add validation method to "jquery validation plugin"

Hello im using jquery validation plugin to validate my form. I want to add one more rule to the validation, but cant get it to work. Input value should be less or equal previous element value.

It is possible to do it ?

Here is the code -

<input type='text' value='<?php echo $count; ?>' class='input_in_stock' readonly="readonly" />
<input type='text' name='amount[]' id='<?php echo rand(0,99).$id; ?>' size='1' value='<?php echo $count; ?>' class='required input_count' />

$(document).ready(function(){

    $.validator.addMethod('positiveint', function (value) { 
        return (value > 0) && (value != 0) && (value == parseInt(value, 10));
    }, 'Enter a positive integer value.');

    $.validator.addMethod('notmorethan', function (value) { 
        return (value <= $(this).prev().val());
    }, 'abc.');




    $("#cartform").validate({
        rules: {
            "amount[]": {
                required: true,
                positiveint: true,
                notmorethan: true
            }
        },
        errorPlacement: function(error, element) {
            error.appendTo(element.next());
        }
    });

});

p.s. I used this jquery validation plugin fix to make it work with names like this[] http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements

EDIT: found the solution

$.validator.addMethod('notmorethan', function (value, element) { 
    return (value <= $(element).prev().val() );
}, 'abc');

Upvotes: 0

Views: 202

Answers (2)

Winns
Winns

Reputation: 902

found the solution

$.validator.addMethod('notmorethan', function (value, element) { 
    return (value <= $(element).prev().val() );
}, 'abc');

Upvotes: 0

Alok Swain
Alok Swain

Reputation: 6519

See if this fiddle helps- http://jsfiddle.net/alokswain/LSuMA/11/ . I am not sure about the customizations that you are using to use names like amount[], but I guess this approach should pretty much work.

The custom validation methods are just functions, if you use this inside the function body then it would refer to the owner of the function. Now assuming you want to get the previously valid value from the input field, you could store it somewhere in the DOM whenever the whole form is valid, say the previously stored value is called as previousAmountVal. When the value in the field is changed, in the function notmorethan you can access the current value using value parameter and the previously stored value and the previous value using previousAmountVal, thus deciding whether the current value is valid or not. Also, if you do this remember to always update the previousAmountVal when the form is valid.

Upvotes: 1

Related Questions