client side validation with dynamically added field

21,811

Solution 1

In order for Darin's answer to work, I changed the following line:

$.validator.unobtrusive.parse(selector); 

To this:

 $(selector).find('*[data-val = true]').each(function(){
    $.validator.unobtrusive.parseElement(this,false);
 });

Here's the full sample:

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    // don't use the normal unobstrusive.parse method
    // $.validator.unobtrusive.parse(selector); 

     // use this instead:
     $(selector).find('*[data-val = true]').each(function(){
        $.validator.unobtrusive.parseElement(this,false);
     });
    
    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        $('[name="' + elname + '"]').rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            $('[name="' + elname + '"]').rules("add", args);
          }
        });
      }
    });
  }
})($);

$.validator.unobtrusive.parse internally calls parseElement method but each time it sends isSkip parameter to true so with this value

if (!skipAttach) {
    valInfo.attachValidation();
}

this code in jquery.unobtrusive.js does not attach validation to the element and we find only validation data of inputs that were initially present on the page.

Note Darin's answer above is correct and you can find on the blog he referred that many people have solved problem using xhalent's code (posted by darin). why it did not work is beyond my understanding. Moreover, you can find plenty of posts that tell you that just calling

$.validator.unobtrusive.parse(selector) 

is enough for dynamically loaded content to be validated

Solution 2

Simpler Answer:

I am using MVC 4 and JQuery 1.8. I have made it to a modular function which accepts the jQuery object of the newly added element:

function fnValidateDynamicContent($element) {
    var $currForm = $element.closest("form");
    $currForm.removeData("validator");
    $currForm.removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse($currForm);
    $currForm.validate(); // This line is important and added for client side validation to trigger, without this it didn't fire client side errors.
}

For example, if you added a new table with id tblContacts, then you can invoke like this:

fnValidateDynamicContent($("#tblContacts"))

Solution 3

Here's a blog post you may find useful and that should put you on the right track. Extension method taken from there:

/// <reference path="jquery-1.4.4.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

(function ($) {
  $.validator.unobtrusive.parseDynamicContent = function (selector) {
    //use the normal unobstrusive.parse method
    $.validator.unobtrusive.parse(selector);

    //get the relevant form
    var form = $(selector).first().closest('form');

    //get the collections of unobstrusive validators, and jquery validators
    //and compare the two
    var unobtrusiveValidation = form.data('unobtrusiveValidation');
    var validator = form.validate();

    $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
      if (validator.settings.rules[elname] == undefined) {
        var args = {};
        $.extend(args, elrules);
        args.messages = unobtrusiveValidation.options.messages[elname];
        $('[name="' + elname + '"]').rules("add", args);
      } else {
        $.each(elrules, function (rulename, data) {
          if (validator.settings.rules[elname][rulename] == undefined) {
            var args = {};
            args[rulename] = data;
            args.messages = unobtrusiveValidation.options.messages[elname][rulename];
            $('[name="' + elname + '"]').rules("add", args);
          }
        });
      }
    });
  }
})($);

and then:

var html = "<input data-val='true' "+
           "data-val-required='This field is required' " +
           "name='inputFieldName' id='inputFieldId' type='text'/>;
$("form").append(html);

$.validator.unobtrusive.parseDynamicContent('form input:last');

Updated to add fix referenced in blog post comments, otherwise js errors occur.

Share:
21,811
Muhammad Adeel Zahid
Author by

Muhammad Adeel Zahid

Updated on July 09, 2022

Comments

  • Muhammad Adeel Zahid
    Muhammad Adeel Zahid almost 2 years

    I am using jQuery's unobtrusive validation plugin in with ASP.NET MVC. Any fields that are rendered on the server are properly validated.

    However, if I dynamically add a field in the form using JavaScript, it is not validated even though it has the appropriate HTML5 data-* attributes.

    Can anyone guide me in right direction on how I can achieve this goal?