Jquery Validate plugin rules method not working

14,414

Solution 1

Everything is correct except the order. At first you should call validate, and just after that you can call rules.

http://jsfiddle.net/85KR4/3/

Solution 2

Yes, as explained in the accepted answer, you must call .validate() (initialization) before calling the .rules() method.

However:

1) Since .validate() is only the initialization method (only gets called once), there is no need to wrap it inside a click handler. The plugin already automatically captures the click event.

2) In this example case there is no need for a submitHandler that only contains a form.submit() inside, since that's already the default behavior of the submitHandler. Leaving the submitHandler out entirely will yield the same result. Although, if you need to use ajax or perform some other code on submit, then by all means, use the submitHandler.

$(document).ready(function() {

    $('form').validate({
        // other rules and options
    });

    $("#id1").rules("add", {
        required: true,
        minlength: 2,
        messages: {
            required: "Required input"
        }
    });

});

DEMO: http://jsfiddle.net/85KR4/5/ (regular form action called on successful submission)

DEMO 2: http://jsfiddle.net/85KR4/7/ (ajax called on successful submission)

Share:
14,414
th1rdey3
Author by

th1rdey3

Updated on June 04, 2022

Comments

  • th1rdey3
    th1rdey3 almost 2 years

    I have a asp.net form where I am trying to use Jquery Validation plugin. I am trying to add the rules using javascript using the rules method. so i tried something like this

    $('#btnSave').on('click', function () {
        $("#txtAmount").rules("add", {
            required: true,
            minlength: 2,
            messages: {
                required: "Required input",
                minlength: jQuery.format("Please, at least {0} characters are necessary")
            }
        });
        $('form').validate({
            submitHandler: function (form) {
                form.submit();
            }
        });
    });
    

    I have set the ClientIDMode="Static" so that i can use the contorl IDs directly. However, this is not working. Can anyone tell me where is the problem. I can't seem to put my finger on it.

    here is a JsFiddle

  • th1rdey3
    th1rdey3 over 10 years
    I should have tried that first. again, silly me. Thanks for your prompt response.
  • Sparky
    Sparky over 10 years
    Not quite "correct except the order"... the click handler is totally superfluous.
  • Smileek
    Smileek over 10 years
    @Sparky, you're absolutely right. Didn't notice anything but main mistake - my bad.