Using MVC 4 with KnockoutJS. Can I bind unobtrusive validation with a custom knockout binding? I am currently rebinding the validation using a template with afterRender
. I would love to have it automatically added with the binding. Like this:
ko.bindingHandlers.egtZipRep = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
$(element).inputmask("99999", { "placeholder": " " });
egtUniqueNameBinding(element, ++ko.bindingHandlers['uniqueName'].currentIndex);
applyValidationRules(element); // Is it possible to do this here?
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor, context);
}
};
I've tinkered around with it all day. I can't do it without being extremely inefficient.
The way I currently do it, is below. Maybe I should just be happy with it. But I'm guessing people have tried this before.
self.ReferenceAfterRender = function (element) {
bindUnobtrusiveValidation(element);
}
// Bind validation on new content
function bindUnobtrusiveValidation(element) {
// Bind to fields - must be called everytime new field is created
$.validator.unobtrusive.parseDynamicContent(element);
}
$.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();
if (typeof (unobtrusiveValidation) != "undefined") {
$.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);
}
});
}
});
}
parseDynamicContent
helper method when doing AJAX calls. Look through jquery.unobtrusive.js and I'm sure there's a method you can call to add the rules dynamically. – Inerrable