sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-02 14:20:42 26 4
mua khóa gpt4 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;
};

1 Câu trả lời

如果您想使用 extend 删除这些字符,您只需在扩展函数中使用 regularExpression 来验证您的字符串,然后làm mới 具有新值的原始可观察值。
工作示例: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:

 



这是您想要做的事情的简单方法

使用非 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:

 

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

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com