4
votes

I created a a view model and want to validate that model using knockout validation . Here is my view model

function SignInViewModel() {
   var self = this;

   self.userName = ko.observable('').extend({
      required: true,
      pattern: {
         message: 'Username must be a valid email address',
         params: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
      }
   });

   self.password = ko.observable('').extend({
      required: true,
      pattern: {
         message: 'Password must be alpha numeric and 4-8 character long .',
         params: /^(?=.*\d).{4,8}$/
     }
   });

   self.login = function () {
      // Want to call validate function here
      $.post("/account/login", { "userName": self.userName(), "password": self.password() })
         .done(function (result) {
            redirect(result.redirect);
     });
    }
}

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

I want to validate my model when my login function is called .

1

1 Answers

6
votes

Create a validation group like

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

add a computed

self.canLogin = ko.computed(function() {
   return self.errors().length === 0;
});

In your view add this data-bind to your button

data-bind="click: login, enable: canLogin"