【问题标题】:Track change in value of a input in knockout js跟踪淘汰赛js中输入值的变化
【发布时间】:2019-07-13 20:03:16
【问题描述】:

在我的 Knockout.js 应用程序中,我想验证用户输入。我使用了自定义验证

下面是我用来循环遍历数组中每个元素的代码。

result.Settings.filter(function (element) {
    element.DisplayMobile = ko.observable(element.PointsForMobile).extend({ required: { message: 'This field cannot be empty' }, useNumberFloatOnly: "abc", maximumValue: 'abc'});
    element.DisplayWeb = ko.observable(element.PointsForWeb).extend({ required: { message: 'This field cannot be empty' }, useNumberFloatOnly: "abc", maximumValue: 'abc'});

    element.Error = ko.observable(false);
});

下面是视图中的输入

<input type="number" data-bind="value:$data.DisplayWeb,valueUpdate: ['afterkeydown', 'input'],,change:TestValidPoint" class="positiveno" min="0" />
<input type="number" data-bind="value:$data.DisplayMobile,valueUpdate: ['afterkeydown', 'input']" class="positiveno" min="0" />

下面是适合我的 useNumberFloatOnly 验证器。

ko.validation.rules['useNumberFloatOnly'] = {
            validator: function (val, othervalue) {
                var numStr = /^\d*[0-9]\d*$/;

                if (othervalue === "abc") {
                    Settings().filter(function (element) {
                        if (element.DisplayMobile() == "" || element.DisplayWeb() == "") {
                            element.Error(true);

                        }
                        if ((element.DisplayMobile() == val || element.DisplayWeb() == val ) && !numStr.test(val)) {
                            element.Error(true);

                        }
                        else if ((element.DisplayMobile() == val || element.DisplayWeb() == val) && numStr.test(val)) {
                            element.Error(false);
                        }
                    });
                }
                return numStr.test(val);
            },
            message: 'Enter only positive values.Decimals not allowed'
        };

单击保存按钮时,我想检查任何字段是否有任何错误。 我面临的两个问题

1) 如何跟踪输入值的变化?使用什么事件? 这是为了跟踪输入是否有错误以及我是否可以禁用保存按钮。

2) 我尝试的第二件事是在遍历数组时的保存按钮单击事件上,Error observable 始终为 false,即使我在验证器中将值设置为 true。

请指导

谢谢

【问题讨论】:

  • 这无关,但如果您只是更新属性,请使用 forEach 而不是 filter
  • 如果解决了您的问题,请mark the answer as accepted

标签: javascript validation knockout.js knockout-validation


【解决方案1】:

您可以为要验证的所有observables 创建一个errorGroup。然后使用errorGroup.isValid()有条件地enable按钮

const viewModel = function() {
  this.DisplayMobile = ko.observable().extend({ required: true });
  this.DisplayWeb = ko.observable().extend({ required: true });
  
  this.submit = function() {
    if (this.errorGroup.isValid()) {
      alert('submitted');
    } else {
      this.errorGroup.errors.showAllMessages();
    }
  };

  this.errorGroup = ko.validatedObservable({
    DisplayMobile: this.DisplayMobile,
    DisplayWeb: this.DisplayWeb
  });
  
};

ko.applyBindings(new viewModel());
.validationMessage{
  color:red
}
<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>

<fieldset>
  <legend>Details</legend>
  <label>Display Mobile: <input data-bind='value: DisplayMobile' /> </label><br>
  <label>Display Web: <input data-bind='value: DisplayWeb' /> </label>
</fieldset>

<br>
<button type="button" data-bind='click: submit, enable: errorGroup.isValid()'>Submit</button>
<br>
<br> Error count: <span data-bind='text: errorGroup.errors().length'></span>

另一种类似的方法是使用验证组:

 this.errors = ko.validation.group(this):

const viewModel = function() {
  this.DisplayMobile = ko.observable().extend({ required: true });
  this.DisplayWeb = ko.observable().extend({ required: true });
  
  this.submit = function() {
    if (this.errors().length === 0) {
      alert('submitted');
    } else {
      this.errors.showAllMessages();
    }
  };

  this.errors = ko.validation.group(this);
};

ko.applyBindings(new viewModel());
.validationMessage{
  color:red
}
<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>

<fieldset>
  <legend>Details</legend>
  <label>Display Mobile: <input data-bind='value: DisplayMobile' /> </label><br>
  <label>Display Web: <input data-bind='value: DisplayWeb' /> </label>
</fieldset>

<br>
<button type="button" data-bind='click: submit, enable: errors().length === 0'>Submit</button>
<br>
<br> Error count: <span data-bind='text: errors().length'></span>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-13
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2018-08-13
    • 2013-08-14
    相关资源
    最近更新 更多