简体   繁体   中英

Jquery Validate plugin rules method not working

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

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)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM