Search code examples
javascriptknockout.jsknockout-validation

Validate observables within a collection using Knockout Validation


I have a message field and collection of people being bound in an unordered list accompanied each with a drop down list of colors and a default selection.

Validation on the message field works, erase the text and an error is displayed and the error count increases. However, when you change one of the drop down entries to "Choose.." (effectively unselecting the option), you receive a "this field is required" message correctly however the errors object does not appear to be updating. It must obviously have something to do with the fact it's a collection? See what I mean when you press the submit button or view the span data binding.

I also need validation to kick in on dynamically added rows, so when you press 'add another row' I need the errors object to increase on that too.

http://jsfiddle.net/goneale/TJGS3/

Could anybody take a look at this and help me out at all?


Solution

  • Update: With latest version of validation library you can use the live: true option to get it to listen to observableArrays

    grouping: { deep: true, observable: true, live: true }
    

    http://jsfiddle.net/fYrbt/29/

    Old answer:

    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/