Reputation: 35
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:
The only thing I can figure out how to analyze is the missing names:
contacts().length = 0
Upvotes: 0
Views: 256
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