gpt4 book ai didi

javascript - 使用 knockout 扩展器不允许使用字符数组

转载 作者:行者123 更新时间:2023-12-02 14:20:42 26 4
gpt4 key购买 nike

我一直在阅读有关 knockout 扩展器的信息 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 来验证您的字符串,然后更新 具有新值的原始可观察值。
工作示例: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' />

关于javascript - 使用 knockout 扩展器不允许使用字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com