PegR
PegR

Reputation: 35

Knockout validation on a nested collection

I am using the example provided by Knockoutjs.com for the "Contacts Editor".

http://jsfiddle.net/rniemeyer/gZC5k/

I am using the exact same code on my website and now need to validate for missing information on submit.

Here are the validation rules I'd like to implement on the form:

  1. Do not allow submission of the form if ANY of the fields (Name and Phones required) are blank.
  2. Do not allow submission of the form if a Name does not have any Phone numbers (parent without children).
  3. Do not allow submission of the form if there are no Names (completely blank form with no parent)

The only thing I can figure out how to analyze is the missing names:

contacts().length = 0

Upvotes: 0

Views: 256

Answers (1)

TSV
TSV

Reputation: 7641

You can introduce additional flag in your view model, e.g. "isValid":

self.isValid = ko.computed(function() {
    if(self.contacts().length === 0) {
    return false;
  }
  var allContactsHaveNames = self.contacts().filter(function(contact) {
    return contact.firstName() !== "" && contact.lastName() !== "";
  }).length === self.contacts().length;
  return allContactsHaveNames;
});

and make all checks inside it.

Of course, this requires changes in markup:

<button data-bind='click: save, enable: isValid'>Save to JSON</button>

and observable "firstName" and "lastName" fields:

self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function(contact) { return { firstName: ko.observable(contact.firstName), lastName: ko.observable(contact.lastName), phones: ko.observableArray(contact.phones) }; }));

self.addContact = function() {
    self.contacts.push({
        firstName: ko.observable(""),
        lastName: ko.observable(""),
        phones: ko.observableArray()
    });
};

Any additional checks can be added into "isValid" compouted function.

You can check updated jsfiddle.

P.S. You can use Knockout validation, as @Sam.C suggested in the comment.

Upvotes: 1

Related Questions