Search code examples
jqueryasp.netjquery-validateunobtrusive-validation

Adding jQuery validator rules to dynamically created elements in ASP


I've got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can't (multiple fields in the UI generate the value for one hidden field - and this is what is submitted. We can't validate against a hidden field, so we must instead add UI-only validation for the fields the user can see)

Once the fields are dynamically added to the page, I run the following code over the container:

$container.find(".date").rules("add", {
    required: true,
    messages: {
        required: "The date is required"
    }
});

But it doesn't work! Oddly enough, disabling the above code, creating the dynamic elements, then running the code in the browser JS console works, but only the default validation message shows.

I'm at a loss. Any ideas?

I am using jQuery Validation 1.9.0 & the unobtrusive plugin


Solution

  • Now that I understand what's going on with the Unobtrusive plugin side of things (which I understand is related to ASP.NET somehow), here's what you need to do:

    After you add your new element, call $.validator.unobtrusive.parseElement(newElement) and it will get added to the form. As your answer suggested, you need to set the data-val and data-val-required attributes in the new form element.

    So you end up with this:

    //create new form element
    $('form fieldset').append('<br>New Field: '+
         '<input type="text" data-val="true" data-val-required="A date is required." name="newField">'+
         ' * Also required');
    
    //add new rules to it
    $.validator.unobtrusive
      .parseElement($('form').find('input[name="newField"]').get(0));
    

    Shown here: http://jsfiddle.net/ryleyb/LNjtd/2/