4

我创建了一个视图模型,并希望使用敲除验证来验证该模型。这是我的视图模型

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 }
});

我想在调用登录功能时验证我的模型。

4

1 回答 1

6

创建一个验证组,例如

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

添加一个计算

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

在您的视图中,将此数据绑定添加到您的按钮

data-bind="click: login, enable: canLogin"
于 2013-06-25T13:53:09.190 回答