我一直在阅读有关淘汰赛延长器http://knockoutjs.com/documentation/extenders.html
的内容我想弄清楚给定一个输入我想要一个具有特殊字符数组但不允许特殊字符输入的扩展器。但我恐怕无法弄明白我在做什么。
this.firstName = ko.observable("").extend({doNotAllow: ['<','>','%','&']});
ko.extenders.doNotAllow = function(target, doNotAllow) {
/*replace any occurrences specialchars with nothing */
return target;
};
答案 0 :(得分:2)
如果您想使用extend
删除这些字符,只需在扩展程序函数中使用regularExpression
来验证字符串,然后使用新值update
原始观察值。
工作示例:https://jsfiddle.net/kyr6w2x3/26/
使用ko.extend
function AppViewModel(first, last) {
this.firstName = ko.observable(first).extend({ doNotAllow:['<','>','%','&'] });
}
ko.extenders.doNotAllow = function(target, charachters) {
target.validationMessage = ko.observable();
//define a function to do validation for special characters
function validate(newValue) {
// you can change regularExpression based on what you exactly want to be removed by using charachters parameter or just changing below expression
target(newValue.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '') );
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
ko.applyBindings(new AppViewModel("Type Special Characters"));
HTML:
<input data-bind='value: firstName, valueUpdate: "afterkeydown"' />
以下是您想要做的简单方法
使用非ko.extend
function AppViewModel(first) {
var self = this;
self.firstName = ko.observable(first);
self.firstName.subscribe(function (newValue) {
if (newValue) {
self.firstName(newValue.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '') );
}
});
}
ko.applyBindings(new AppViewModel("Type Special Characters"));
HTML:
<input data-bind='textInput: firstName' />