0

I am trying to validate my model manually by calling self.isModelvalid in my test and assuming that I would return true , because before calling it I assigned test values to all properties in my model . here is how I call in my test

        listingViewModel = new ListingViewModel();
        listingViewModel.country('a');
        listingViewModel.city('a');
        listingViewModel.cummunity('a');
        listingViewModel.subCummunity('a');
        listingViewModel.postCode('1');        
        expect(listingViewModel.isModelValid()).toBe(true);

and this is my source class where my model and all methods exists :

        function validateModel(model) {
      var self = model;
       for (var prop in self) {
       if (self.hasOwnProperty(prop)) {
         if (!(self[prop].isValid())) {
            return false;
          }
       }
    }

   return true;

 }

   function ListingViewModel() {
   var self = this;
    self.country = ko.observable('').extend({required : true});
   self.city = ko.observable('').extend({ required: true });
  self.cummunity = ko.observable('').extend({ required: true });
   self.subCummunity = ko.observable('').extend({ required: true });
    self.postCode = ko.observable('').extend({ required: true });

    self.isModelValid = function () {

      validateModel(self);

    };

   self.addListing = function () {

    };
   }


    ko.validation.configure({
   decorateElement: false,
   errorElementClass: "error",   // class name
   insertMessages: false,
   grouping: { deep: true, observable: true }
  });

When when i run it says

listingViewModel.isModelValid() TypeError: self[prop].isValid is not a function

and i think this error occurs when it validateModel try to validate isModelValid and it fails because isModelValid is not a function its property .

So how to validate only properties in a knockout model .

Thanks

Ancient
  • 3,007
  • 14
  • 55
  • 104

1 Answers1

1

Technically the ko.observable is also a function. So in your case every member of the ListingViewModel is a function.

What you need is to check for whether the isValid property exists on a given member.

Luckily the knockout validation plugin has a nice utility function to check this, namely: ko.validation.utils.isValidatable.

So you need to modify your validateModel to check for the existence of isValid property with the above mentioned function:

 function validateModel(model) {
      var self = model;
       for (var prop in self) {
       if (self.hasOwnProperty(prop)) {
         if (ko.validation.utils.isValidatable(self[prop]) 
             && !(self[prop].isValid())) {
            return false;
          }
       }
    }

Demo JSFiddle.

nemesv
  • 138,284
  • 16
  • 416
  • 359