client side validation with dynamically added field
Asked Answered
C

3

20

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?

Chancy answered 11/5, 2011 at 13:59 Comment(0)
C
10

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

Chancy answered 12/5, 2011 at 12:30 Comment(2)
For anyone else using this, I recommend you alter one more thing about it, especially if you're using this on dynamic collections in MVC: $('[name=' + escapeAttributeValue(elname) + ']') where escapeAttributeValue does makes the name jquery selector-safe: return value.replace(/([!"#\$%&'()*\+,\.\/:;<=>\?@[\\]\^`\{\|\}~])/g, '\\$1');Patrickpatrilateral
$.validator.unobtrusive.parse(selector) only works for a new added form. If you already have an existing form and insert new input fields to that form, it won't work.Defoliant
V
21

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"))
Vladivostok answered 28/2, 2013 at 6:54 Comment(2)
Great find! In my limited testing this seems to work. Note that "currform" in the last line of code should be currForm (capital F).Kamchatka
I assume you meant fnValidateDynamicContent($("#tblContacts")) ?Hula
R
12

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.

Rochdale answered 11/5, 2011 at 14:6 Comment(2)
when i debug it a little bit, it manages to skip both if and else portion of the conditionChancy
further debugging reveals that var unobtrusiveValidation = form.data('unobtrusiveValidation'); is source of error and not getting the rules for newly added fields.Chancy
C
10

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

Chancy answered 12/5, 2011 at 12:30 Comment(2)
For anyone else using this, I recommend you alter one more thing about it, especially if you're using this on dynamic collections in MVC: $('[name=' + escapeAttributeValue(elname) + ']') where escapeAttributeValue does makes the name jquery selector-safe: return value.replace(/([!"#\$%&'()*\+,\.\/:;<=>\?@[\\]\^`\{\|\}~])/g, '\\$1');Patrickpatrilateral
$.validator.unobtrusive.parse(selector) only works for a new added form. If you already have an existing form and insert new input fields to that form, it won't work.Defoliant

© 2022 - 2024 — McMap. All rights reserved.