user3173022
user3173022

Reputation: 57

jQuery validation: a field that must to be 0 or multiple of 20

i'm trying to validate (jQuery validation plugin) a field musts to be 0 or multiple of 20 (0, 20, 40, 60, ...). Anybody knows how to make it?

Upvotes: 0

Views: 2433

Answers (4)

Shiju Joy
Shiju Joy

Reputation: 1

$.validator.addMethod("multiples", function (value, element, param) {
    return this.optional(element) || parseInt(value, 10) % param == 0
}, jQuery.validator.format("Please enter a multiple of {0}"));

Upvotes: -1

Staci S
Staci S

Reputation: 31

This implementation allows you to set any multiple to validate:

$.validator.addMethod("multiples", function (value, element, param) {
    return this.optional(element) || parseInt(value, 10) % param == 0
}, jQuery.validator.format("Please enter a multiple of {0}"));

Then use either of these formats to invoke the validation (multiples of 12 allowed in the examples):

    <input type="text" name="qty" class="required" multiples="12">

or

$("#myform").validate( {
 rules: {
        qty : {
            required: true,
            multiples: 12
        }
    }
});

Upvotes: 2

Sionnach733
Sionnach733

Reputation: 4736

Use Modulus:

var num = //your field num
if(num%20 == 0){
    //code here
}

DEMO

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Add a custom validation method

jQuery.validator.addMethod("special", function (value, element) {
    return this.optional(element) || parseInt(value, 10) % 20 == 0
}, 'The value must be 0 or a multiple of 20');

then

$('form').validate({
    rules: {
        field: {
            required: true,
            digits: true,
            special: true
        }
    },
    messages: {}
});

Demo: Fiddle

Upvotes: 3

Related Questions