Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to dynamically add a validation rule

Tags:

jquery

I'm trying to dynamically add a validation rule to some dynamic controls:

$("input[id*=Hours]").rules("add", "required");

However this line gives me the following error:

$.data(element.form, "validator") is null

Defining rules the static way with the validate function works fine. What am I doing wrong?

Thanks, Justin

like image 427
Justin Avatar asked Jun 13 '10 21:06

Justin


3 Answers

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

like image 52
Nick Craver Avatar answered Nov 08 '22 03:11

Nick Craver


To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like

$("#DivIdContainer .classToValidate").each(function () {
    $(this).rules('add', {
        required: true
    });
});
like image 39
Rick Avatar answered Nov 08 '22 03:11

Rick


As well as making sure that you have first called $("#myForm").validate();, make sure that your dynamic control has been added to the DOM before adding the validation rules.

like image 4
row1 Avatar answered Nov 08 '22 05:11

row1