【问题标题】:Knockout custom validation: How to check if observable is equal to a specific value?淘汰赛自定义验证:如何检查 observable 是否等于特定值?
【发布时间】:2019-07-05 12:18:06
【问题描述】:

我是 Knockout.js 的新手,我想检查我的表单字段是否具有特定值。实际上,我只检查它是否需要。我该怎么办?

这是我的 html 页面中的内容:

 <div data-bind="visible: !Vm.isValid()" class="text-danger">Fill each field to send data, otherwise show this message</div>

 <input data-bind="enable: Vm.isValid()" type="button" value="Send data!" />

这就是我的 vm.js 文件的样子:

 window.Vm = ko.validatedObservable({
     name : ko.observable().extend({ required: true })
 });            

我会做这样的东西,但我不知道怎么做:

 var found = "found";
 window.Vm = ko.validatedObservable({
    name: ko.observable().extend({
       required: true,
       function: {
          if (this.val() == found)
             return true; // invalid value, can't submit my form
       }
    })
 });

【问题讨论】:

    标签: javascript knockout.js knockout-validation


    【解决方案1】:

    您可以像这样使用自定义validator (Documentation):

    var found = "found";
    
    var Vm = ko.validatedObservable({
      name: ko.observable().extend({
        required: {
          message: "This is a required field",
        },
        validation: {
          validator: (val, paramValue) => {
            // "val" has the value entered in the field
            // "paramValue" has the value set in "params"
            return val === paramValue
          },
          message: "The value is not " + found,
          params: found
        }
      })
    });
    
    ko.applyBindings(Vm)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
    
    <input type="text" data-bind="value: name" />

    【讨论】:

      【解决方案2】:

      我实际上建议不要使用 Knockout Validation 库,因为它已经多年没有维护了。对于一个不再存在的问题,这是一个过时的解决方案。在 2019 年,您可以只使用每个现代浏览器原生的表单验证。只需在表单字段中添加required 属性,如果未填写所有必填字段,表单将不会提交。

      如果你想让它更有活力,你可以这样做:

      function ViewModel() {
          var vm = this;
      
          vm.name = ko.observable();
          vm.required = ['name', 'email'];
      
          vm.isRequired = isRequired;
      
          function isRequired(field) {
              return vm.required.indexOf(field) > -1;
          }
      }
      

      并使用attr 绑定根据视图模型中所需元素的数组设置required 属性。

      <input type="text" data-bind="textInput: name, attr: { required: isRequired('name') }">
      

      【讨论】:

        【解决方案3】:

        我取数据为["A","B"],根据相同的数据进行搜索。

        ko.extenders.required = function(target, overrideMessage) {
            //add some sub-observables to our observable
            target.hasError = ko.observable();
            target.validationMessage = ko.observable();
            target.data = ko.observableArray(["A","B"]);
         		target.found = ko.observable();
            target.foundMessage = ko.observable();
            //define a function to do validation
            function validate(newValue) {
               target.hasError(newValue ? false : true);
               target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
               target.found(target.data().find(function(element){ return newValue==element;}));
               target.found()?target.foundMessage("element has found"):target.foundMessage("element has not found");
            }
         
            //initial validation
            validate(target());
         
            //validate whenever the value changes
            target.subscribe(validate);
         
            //return the original observable
            return target;
        };
         
        function AppViewModel(first) {
            this.firstName = ko.observable(first).extend({ required: "" });
        }
         
        ko.applyBindings(new AppViewModel("C"));
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
        <p data-bind="css: { error: firstName.hasError }">
            <input data-bind='value: firstName, valueUpdate: "afterkeydown"' />
            <span data-bind='visible: firstName.hasError, text: firstName.validationMessage'> </span>
            <span data-bind='visible: (!firstName.hasError()), text: firstName.foundMessage'> </span>
        </p>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-01
          • 2018-04-19
          • 2016-08-13
          • 1970-01-01
          • 1970-01-01
          • 2017-11-29
          • 2015-06-25
          • 2014-02-21
          相关资源
          最近更新 更多