使用敲除扩展程序不允许使用字符数组

using knockout extender to not allow an array of characters

本文关键字:字符 数组 不允许 扩展 程序      更新时间:2023-09-26

我一直在读关于淘汰赛扩展器的文章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' />