Search code examples
knockout.jsknockout-mapping-pluginknockout-validation

Knockout using Mapping and Validation Plugins together. Getting client errors


I'm using knockout js to construct my application with asp.net mvc 4 on the backend. We are using knockout.mapping to populate the observables from MVC Service calls

Now I'm trying to add validation using the Knockout.Validation plugin as follows:

self.sDetail(ko.mapping.fromJS(s));
var validationOptions = { 
                          insertMessages: true, 
                          decorateElement: true,      
                          errorElementClass: 'errorFill' 
                         };
ko.validation.init(validationOptions);
self.sDetail.Year.extend({ required: true });

When I run it I get the following error:

Error: Unable to get property 'extend' of undefined or null reference

When I debug I find that the sDetail appears empty. When I applyBindings the inputs are populated correctly. At what point to I have access to the propertys of the ko viewmodel. Is there a way around this issue?


Solution

  • Found a solution here: Knockout Mapping Validation

    basically have to extend the properties in the call to mapping

    var validationMapping = {
    // customize the creation of the name property so that it provides validation
    Year: {
        create: function(options) {
            return ko.observable(options.data).extend( {required: true} );
        }
    }
    };
    
    
      self.sDetail(ko.mapping.fromJS(s,validationMapping));
     var validationOptions = { 
                          insertMessages: true, 
                          decorateElement: true,      
                          errorElementClass: 'errorFill' 
                         };
      ko.validation.init(validationOptions);
    

    self.sDetail.Year.extend({ required: true });