Search code examples
javascriptjqueryvalidationclient-sideclient-side-validation

jQuery validation for client-side dynamic controls


I have controls that are dynamically added via javascript. I cannot set the class on these controls to “required” because I need the flexibility to place the error messages where I will. When I add these controls, I loop through all that I need required, and call

$("#dynamicControlID").rules("add", {required:true});

The problem comes when I try to validate the form. When I call

$("#form1").validate()

any non-dynamic controls that have the class “required” specified will validate with a nice message that says “this field is required.” The controls that have been added dynamically do not show any message, and the validate function returns true even if they’re empty. The real confusion comes when I validate the dynamic controls individually. If I call

$("#dynamicControlID").valid()

it will return false, and display the error message by the input. I do call

$("#form1").valid()

before I do anything with the dynamic controls.

Am I missing something here? What I would like is to call

$("#form1").valid() 

and have the error messages show for all my dynamically added controls.


Solution

  • You're on the right track, but when you want to add rules to the new element, you have to have already called $('#form1').validate();.

    So a common setup is something like this:

    $('#form1').validate({
       //your options
    });
    
    $('#dynamicControlID').rules('add',{required:true});