Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validator addMethod not working correctly

I am using a new validation rule with the jQuery validation. It is somehow not applied though? It is contained within a javascript file that is included after jquery.validate.js. When should I include the js file that contains my custom rules for them to be applied?

When I enter 0.1 into an input that should validate against this nothing happens, the console.log isnt hit neither is the alert.

$(document).ready(function(){
    jQuery.validator.addMethod('integer', function(value, element, param) {
        console.log(value); alert("hey");

        return (value != 0) && (value == parseInt(value, 10));
    }, 'Please enter a non zero integer value!');
});

HTML

<input class="required number integer valid" type="text" data-type="int" value="1" name="Default.MinArrivals" title="">

The classes required and number work perfectly, it is just my integer method that doesn't work correctly.

like image 387
Chris Avatar asked Dec 17 '25 03:12

Chris


1 Answers

It seems to be working for me:

http://jsfiddle.net/2VJZT/

Please show the rest of your code.

jQuery:

$(document).ready(function () {

    jQuery.validator.addMethod('integer', function (value, element, param) {
        return (value != 0) && (value == parseInt(value, 10));
    }, 'Please enter a non zero integer value!');

    $('#myform').validate({
        rules: {
            field1: {
                required: true,
                integer: true
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="submit" />
</form>

Quote: When should I include the js file that contains my custom rules for them to be applied?

As long as:

1) your code (or file) comes after you've properly included jQuery and jQuery Validate plugin (in that order).

AND

2) your code is all contained within a document.ready function.

Notes: The ordering of .validator.addMethod and .validate() do not matter with respect to each other as long as you follow 1 & 2. http://jsfiddle.net/jp93D/

like image 56
Sparky Avatar answered Dec 19 '25 19:12

Sparky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!