【问题标题】:How to validate model in knockout validation如何在淘汰赛验证中验证模型
【发布时间】:2013-06-22 07:36:40
【问题描述】:

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

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

我想在我的登录函数被调用时验证我的模型。

【问题讨论】:

    标签: knockout.js knockout-2.0 knockout-validation


    【解决方案1】:

    创建一个验证组,如

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

    添加一个计算

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 2012-11-04
      • 1970-01-01
      • 2011-08-09
      • 2015-02-03
      • 2015-02-01
      • 2017-01-27
      • 1970-01-01
      • 2012-12-05
      相关资源
      最近更新 更多