Thursday, October 18, 2012

"Dynamic" deep validation with KnockoutJS model

In this article, Knockout Model and Validating "inner" Models, we have seen how deep validation is done. Here is a snippet of that validation: = function () {
if (self.errors().length != 0) { //verifying the errors attribute using the count of errors
self.errors.showAllMessages(); //displaying the corresponding error messages
return; //returning the control providing user a chance to correct the issues
In the above method, we are simply invoking the showAllMessages method from the errors member. This will work for on occasion but sometimes this will fail and the validation error messages will not be displayed. In this situation, there is a workaround using which we can achieve this validation functionality working. The workaround is to add errors member to javascript class and then invoike the showAllMessage method for each of the instance of the class as shown below:
function Contact(id, phoneType, phone) {
var self = this;
self.ClientId = ko.observable(id);
self.PhoneType = ko.observable(phoneType).extend({ required: true });
self.Phone = ko.observable(phone).extend({ required: true });
self.errors =; //adding the errors object for javascript class making each instance to hold the error individually
function ClientModel (id, firstName, lastName, email, contacts) {
var self = this;
self.Id = ko.observable(id);
self.FirstName = ko.observable(firstName).extend({ required: true, maxLength: 50 });
self.LastName = ko.observable(lastName).extend({ required: true, maxLength: 50 });
self.Email = ko.observable(email).extend({ maxLength: 50, email: true });
self.Contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (aContact) { return aContact; }));
Next we will update the save method as follows to perform the validation: = function () {
       var errorCount = 0;
ko.utils.arrayForEach(self.Contacts(), function(contact){
errorCount = errorCount + 1;
if (errorCount != 0) {
       //save code block
Hope this helps.

No comments: