How to check an array?

I am trying to use a knockout verification file to validate an array of objects. It’s not easy for me how to form a validation group for an array of observables. The only way I managed to get it to work is ( JSFIDDLE Enabled ):

var Note = function () { var self = this; self.name = ko.observable().extend({ required: true }); }; var viewModel = function() { var self = this; self.notes = ko.observableArray([new Note(), new Note()]); self.validatedObservables = function() { var arr = []; ko.utils.arrayForEach(self.notes(), function(note) { arr.push(note.name); }); return arr; }; self.errors = ko.validation.group(self.validatedObservables()); self.submit = function () { if (self.errors().length != 0) { self.errors.showAllMessages(); } }; }; ko.applyBindings(new viewModel()); 

It seems my approach is overly detailed. According to the source code, you can simply pass the observed value to ko.validation.group:

 self.errors = ko.validation.group(self.notes()); 

But that will not work.

+8
knockout-validation
source share
2 answers

There is a configuration option for deep (recursive) grouping. It can be set globally using ko.validation.init( { grouping: { deep: true } } ) or in the group call itself, for example: self.errors = ko.validation.group( self.notes(), {deep: true} );

Updated fiddle here: http://jsfiddle.net/KHFn8/4116/

By the way, the way you did this can be written in a much shorter form:

 self.errors = ko.validation.group( ko.utils.arrayMap(self.notes(), function(note) { return note.name })); 

Edit : My violin no longer works with the latest version of the KO check. Here is the same fiddle using the latest version at the time I gave the answer (June 2012): http://jsfiddle.net/KHFn8/4117/

+14
source share

I have a low reputation to comment. So here is another answer. The answer with scripts provided by anti-shock seams will no longer work. (The link to knockout.js was broken, but even after fixing it and adding a working link for knockout 3.0, it still didn't work)

I added ko.computed around ko.validation.group () and made it work this way.

 self.errors = ko.computed(function() { return ko.validation.group(self.notes(), { deep: true })}); 

http://jsfiddle.net/bezFR/17/ (updated)

I guess there is a better way to do this, but at the moment it solves my problem and I am looking forward to fixing / looking at a better solution :)

+2
source share

All Articles