采用淘汰赛扩展不允许字符
问题描述:
我一直在阅读有关淘汰赛扩展的阵列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;
};
答
如果你想使用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' />
嗯?目前你的代码根本不会做任何事情。你有没有尝试过任何一种实现?让我们知道具体出了什么问题,这样我们可以更轻松地帮助您。 – Jeroen