Search code examples
knockout.jsknockout-validation

Knockoutjs only validate chind class


I use Knockoutjs 3.0.0 and Knockoutjs-Validate, most time they work good. Now I have problem when I try to validate partial View Model. Like this:

 function DataViewModel() {
      var self = this;

      self.username = ko.observable("").extend({ required: {message:"User name is required!" }});
      self.password = ko.observable().extend({ required: {message:"Password is required!" }});

      self.login = function () {

          if (self.isValid()) {
              self.errors.showAllMessages();
              return false;
          }
           $("#loginform").submit();
      };
  }

and I also have Page Viewmodel which control page attribute.

  function PageViewModel(){
    var self=this;
    self.contentheader=ko.observable("Login");
    self.usernamelabel = ko.observable("User Name");
    self.passwordlabel = ko.observable("Password");
  }

I create ViewModel like this:

 function ViewModel()
  {
    var self=this;
    self.data= ko.validatedObservable(new DataViewModel());
    self.page= new PageViewModel();
  }

finally I bind to KO var vm = new ViewModel(); ko.applyBindings(vm);

Why I do program like this is: in DataViewModel, I store data which will be pass or load from server, Page view model I control this page behave, I should do validate for DataViewModel when user submit data to server. But it doesn't work, I saw KO model raise error like this

 TypeError: obsv is undefined

Anyone can help?


Solution

  • In your case, you can handle the validation for your DataViewModel within that model. Add an observable within your model to track the validation, like so

    self.errors = ko.validation.group(self);

    and change your DataViewModel instance in your primary viewmodel to be a normal ko.observable instead of a validated observable. I've made a fiddle with the complete code.