我正在尝试使用带有Knockout和jQuery Validate的绑定处理程序,但是当我提交表单时,页面重新加载,不会验证并且不会在我的视图模型上调用该方法。
有人可以告诉我我错过了什么吗?
这是我的约束力
ko.bindingHandlers.validateEmailForm = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).validate({
errorLabelContainer: $("#updateEmailFormAlert"),
wrapper: 'li',
rules: {
email: {
required: true,
email: true
},
emailConfirm: {
email: true,
equalTo: "#email",
}
},
messages: {
email: {
required: "Email is required",
email: "Please enter a valid email address"
},
emailConfirm: {
required: "Confirm Email is required",
email: "Please enter a valid confirm email address",
equalTo: "Confirm Email must match Email"
}
},
submitHandler: function() {
viewModel.updateUserEmail();
}
});
}
};
答案 0 :(得分:0)
好的,所以我所要做的就是在创建ViewModel实例时创建一个变量,以便我可以引用我的ViewModel中的函数。
var userViewModel = new UsersViewModel();
ko.applyBindings(userViewModel);
然后在我的submitHandler
中 // activate the jQuery Validate on the form
ko.bindingHandlers.validateEmailForm = {
update: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {
$(element).validate({
errorLabelContainer: $("#updateEmailFormAlert"),
wrapper: 'li',
rules: {
email: {
required: true,
email: true
},
emailConfirm: {
email: true,
equalTo: "#email",
}
},
messages: {
email: {
required: "Email is required",
email: "Please enter a valid email address"
},
emailConfirm: {
required: "Confirm Email is required",
email: "Please enter a valid confirm email address",
equalTo: "Confirm Email must match Email"
}
},
submitHandler: function() {
userViewModel.updateUserEmail(data);
return false;
}
});
}
};