knockout.js - Issues with knockout observable array validation -
i have issue validation rule put on observablearray elements. i'm using custom message template display errors, issue doesn't displayed on when errors there, however, can see '*' against relevant field. following model:
function viewmodel(item) { var parse = json.parse(item.d); var self = this; this.id = ko.observable(parse.id).extend({ required: { params: true, message: "id required" }}); this.name = ko.observable(parse.name); this.weeklydata = ko.observablearray([]); var records = $.map(parse.weeklydata, function (data) { return new data(data) }); this.weeklydata(records); } var data = function (data) { this.val = ko.observable(data).extend({ min: { params: 0, message: "invalid minimum value" }, max: { params: 168, message: "invalid maximum value" } });
here validation configuration i'm using:
// enable validation ko.validation.configure({ registerextenders: true, messagesonmodified: false, insertmessages: true, parseinputattributes: false, messagetemplate: "custommessagetemplate", grouping: { deep: true } }); ko.validation.init();
any custom message template goes this:
<script id="custommessagetemplate" type="text/html"> <em class="errormsg" data-bind='visible: !field.isvalid()'>*</em> </script> <ul data-bind="foreach: errors"> <li class="errormsg" data-bind="text: $data"></li> </ul>
with implementation, don't see validation messages in custom template. if remove configuration deep: true, doesn't validate observable array elements, other observable(id) , message displayed properly.
i'm confused , bit stuck, appreciate if can help/
thanks in advance.
what understand question trying validate observablearray entries, if entry in weeklydata
observablearray fails following condition:
arrayentry % 15 === 0
you want show error message. if case, following custom validator can job :
var fminincrements = function (valuearray) { var check = true; ko.utils.arrayfirst(valuearray, function(value){ if(parseint(value, 10) % 15 !== 0) { check = false; return true; } }); return check; };
and have apply validator on observablearray (no need set validation on individual entries of array). validator takes array input , validate each entry, if 1 entry fails validation retrun false , see error message.
your viewmodel looks :
function viewmodel() { var self = this; self.weeklydata = ko.observablearray([ 15, 40 ]).extend({ validation: { validator: fminincrements, message: "use 15 min increments" } }); self.errors = ko.validation.group(self); }
and here working fiddle.
Comments
Post a Comment