我创建了一个视图模型,并希望使用敲除验证来验证该模型。这是我的视图模型
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 }
});
我想在调用登录函数时验证我的模型。
答案 0 :(得分:6)
创建一个类似
的验证组self.errors = ko.validation.group(self);
添加计算
self.canLogin = ko.computed(function() {
return self.errors().length === 0;
});
在您的视图中,将此数据绑定添加到按钮
data-bind="click: login, enable: canLogin"