Skip to content

Instantly share code, notes, and snippets.

@joelpurra
Created April 11, 2012 15:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joelpurra/2360001 to your computer and use it in GitHub Desktop.
Save joelpurra/2360001 to your computer and use it in GitHub Desktop.
$.validator.unobtrusive.parseDynamicContent by XHalent, modified to keep a reference to the jQuery selector/context object
/// <reference path="../jquery-1.7.js" />
/// <reference path="../jquery.validate.js" />
/// <reference path="../jquery.validate.unobtrusive.js" />
// Originally by XHalent, @xhalent
// http://xhalent.wordpress.com/
// http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
// Modified by Joel Purra
// http://joelpurra.com/
// https://gist.github.com/gists/2360001
(function ($, undefined) {
$.validator.unobtrusive.parseDynamicContent = function (selector) {
var $selector;
if (selector instanceof jQuery) {
$selector = selector;
}
else {
$selector = $(selector);
}
if ($selector.length == 0) {
return;
}
//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];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']", $selector).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];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']", $selector).rules("add", args);
}
});
}
});
};
})(jQuery);
@joelpurra
Copy link
Author

Just figured that I would paste a slightly modified version that I used in a previous project. Pasted the original first, for comparison.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment