使用敲除扩展程序不允许使用字符数组
using knockout extender to not allow an array of characters
我一直在读关于淘汰赛扩展器的文章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扩展
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扩展
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' />
相关文章:
- 从指定范围创建字符数组
- 第一个字第一个字符第二个字第二个字符,一直到数组结束
- 正在转义javascript数组中的html字符
- 为什么Angularjs服务返回的是字符数组而不是对象数组
- 将组成单词的字符添加到数组的开头
- 用javascript将字符串连接到数组中
- 用Objective-C将JSON解析成C风格的字符数组
- 打破ng中的字符数组,重复并设置每个字符自己的输入标记
- 计算JavaScript中句子(数组)中字符(数组)的出现次数
- 将句子字符串拆分为单词数组,然后将单词数组拆分为单词数组中的字符数组
- 使用JavaScript将字符串转换为字符数组
- 从占转义字符的字符数组创建字符串
- 如何从字符数组中创建3个唯一值
- 在Chrome下,Base-64字符数组异常的无效长度
- 将正则表达式与字符数组匹配
- 通过字符数组转义字符串
- 替换字符串中的字符数组
- 如何将Javascript字符串转换为八位字节/字符数组
- 在字符数组中循环
- 使用敲除扩展程序不允许使用字符数组