跟踪敲除js中输入值的变化

时间:2019-02-20 07:40:27

标签: javascript validation knockout.js knockout-validation

在我的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)我尝试的第二件事是遍历数组时在保存按钮单击事件上,即使我在验证器中将值设置为true,可观察到的 Error 始终为false。< / p>

请指导

谢谢

1 个答案:

答案 0 :(得分:0)

您可以为要验证的所有errorGroup创建一个observable。然后使用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>