jQuery - How to dynamically add a validation rule

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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
    });
});

Solution 3 - Jquery

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.

Solution 4 - Jquery

The documentation says:

> 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.

Did you do that? The error message kind of indicates that you didn't.

Solution 5 - Jquery

In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below

//remove validations on entire form
$("#yourFormId")
    .removeData("validator")
    .removeData("unobtrusiveValidation");

//Simply add it again
$.validator
    .unobtrusive
    .parse("#yourFormId");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustinView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryRickView Answer on Stackoverflow
Solution 3 - Jqueryrow1View Answer on Stackoverflow
Solution 4 - JqueryPeter JaricView Answer on Stackoverflow
Solution 5 - JqueryMohsinView Answer on Stackoverflow