Mdb*_*Mdb 18 customization knockout.js knockout-validation
我正在使用Asp.net MVC3和knockoutjs库.我需要做一些客户端验证.我正在探索淘汰赛验证插件.
所以我在我的js代码中声明了以下ko.observable值:
var numberValue = ko.observable().extend({ number: true })
Run Code Online (Sandbox Code Playgroud)
这是我的观点部分:
<input data-bind = "value: numberValue " />
Run Code Online (Sandbox Code Playgroud)
当用户输入一些不是数字的值时,会显示错误消息:"请输入一个数字".我可以显示不同的错误消息但仍使用本机规则吗?我不想为此编写自定义验证逻辑.任何有关工作示例的帮助将不胜感激.谢谢!
mad*_*kay 34
以下是创建验证扩展程序的代码.
addExtender: function (ruleName) {
ko.extenders[ruleName] = function (observable, params) {
//params can come in a few flavors
// 1. Just the params to be passed to the validator
// 2. An object containing the Message to be used and the Params to pass to the validator
//
// Example:
// var test = ko.observable(3).extend({
// max: {
// message: 'This special field has a Max of {0}',
// params: 2
// }
// )};
//
if (params.message) { //if it has a message object, then its an object literal to use
return ko.validation.addRule(observable, {
rule: ruleName,
message: params.message,
params: params.params || true
});
} else {
return ko.validation.addRule(observable, {
rule: ruleName,
params: params
});
}
};
},
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,所有扩展器都可以使用params和自定义消息接收params对象或对象文字.所以在你的情况下.
var numberValue = ko.observable().extend({ number: {
message: "some custom message",
params: true
} })
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
小智 33
你可以像这样添加validate属性
emailAddress: ko.observable().extend({ // custom message
required: { message: 'Please supply your email address.' }
}),
Run Code Online (Sandbox Code Playgroud)