2
votes

i can't find any solution to this, so here's my problem:

I have set up validation for a small form, where you can add items to a collection (observableArray, actual saving to DB later).

The validation works fine for the first item and validation messages show up, but for the second time the validation messages won't show up (validation itself works, you can't add items).

here's what i do:

  1. set up validation in newSchool object, for example

    self.City = ko.observable(item ? item.City : '').extend(
    {
        required: true
    });
    
  2. build validation group in MainViewModel

    self.schoolErrors = ko.validation.group({ schools: self.newSchool }, { deep: true });

  3. in MainViewModel: check for errors, else push into collection, initialise newSchool observable with new default values

    self.addSchool = function () {
        if (self.schoolErrors().length > 0) {
            self.schoolErrors.showAllMessages();
            return;
        }
        self.schools.push(self.newSchool());
        self.newSchool(new School());
        self.newSchool().load();
        self.schoolErrors = ko.validation.group({ schools: self.newSchool }, { deep: true  }); };
    

For debugging reasons i printed out isValid and isModified values of the validated observables in the school object. these seem to be fine. after i inserted the first item, isValid and isModified are both returned to false .

only problem, as mentioned, no validation messages are shown up any more.

also strange for me: i don't use custom validation message templates, except in one case, where i need to validate against a computed field. this shows up, but the "build-in" validation messages don't.

any idea?

2

2 Answers

2
votes

If just added a pull request to knockout-validation which fixes that problem that knockout.validation.group does not react to changes in observable arrays.

https://github.com/Knockout-Contrib/Knockout-Validation/pull/223

0
votes

Sadly the group does not get reevaluated when a new item is inserted. Subscribe to the array and do it explicit.

this.items.subscribe(function() {
     this.errors = ko.validation.group(this);
     this.errors.showAllMessages();
}, this);

http://jsfiddle.net/fYrbt/

In the fiddle I'm using Github as a CDN, so if the fiddle does not work wait and reload.