我有一个使用knockout绑定的asp.net mvc3项目,其中我对一张表进行批量编辑。我想在保存数据时进行必填和数字验证。有没有更简单的方法来进行knockout验证。 PS: 我没有使用表单。
我有一个使用knockout绑定的asp.net mvc3项目,其中我对一张表进行批量编辑。我想在保存数据时进行必填和数字验证。有没有更简单的方法来进行knockout验证。 PS: 我没有使用表单。
可以看看Knockout-Validation,它干净地设置和使用了在 Knockout 文档 中所描述的内容。在: Live Example 1: Forcing input to be numeric下面。
您可以在Fiddle中查看实时示例
更新: Fiddle已更新为使用最新的KO 2.0.3和ko.validation 1.0.2,使用Cloudfare CDN网址。
设置 ko.validation:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
使用扩展器来设置验证规则。例如:
var viewModel = {
firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
lastName: ko.observable().extend({ required: true }),
emailAddress: ko.observable().extend({ // custom message
required: { message: 'Please supply your email address.' }
})
};
ko.extenders.required = function (target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
然后在你的viewModel中扩展你的observable:
self.dateOfPayment: ko.observable().extend({ required: "" }),
Knockout.js的验证很方便,但不够健壮。您总是需要创建服务器端验证副本。在您的情况下(因为您使用knockout.js),您正在异步地向服务器发送JSON数据,然后再将其发送回来,因此您可以让用户认为他看到了客户端验证,但实际上它是异步服务器端验证。
在这里查看示例upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 这是一个“创建订单”的链接。尝试单击“保存”并使用产品。 此示例使用upida库完成(该库有spring mvc版本和asp.net mvc版本),可在codeplex上找到。