使用knockout扩展器不允许一个字符数组

时间:2016-07-29 18:16:23

标签: javascript knockout.js

我一直在阅读有关淘汰赛延长器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 个答案:

答案 0 :(得分:2)

如果您想使用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' />