knockout.js 对 observableArray 进行验证以要求所有项目(无空字段)

knockout.js validation on observableArray to require all items (no empty fields)

我写了下面这个使用knockout的例子

HTML

<script id="customMessageTemplate" type="text/html">
    <em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
    <legend>User: <span data-bind='text: errors().length'></span> errors</legend>
    <label>First name: <input data-bind='value: firstName'/></label>
    <label>Last name: <input data-bind='value: lastName'/></label>    

    <table>
    <thead>
        <tr><th>Value</th></tr>
    </thead>
    <tbody data-bind="foreach: captcha">
        <tr>
            <td><input data-bind="value: value" type="test" /></td>
        </tr>
    </tbody>
</table>

<button type="button" data-bind='click: submit'>Submit</button>

淘汰赛

ko.validation.rules.pattern.message = 'Invalid.';


ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});


var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),


    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};


viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);

我应该向 observableArray 添加什么,以要求此数组中的所有项都像通常的 observable 对象一样重新输入示例中的 FirstName 和 LastName 字段?

您可以像这样添加您的 custom validation rule

ko.validation.rules['noEmptyValues'] = {
    validator: function (arr) {
        return arr.every(function(v) {
          return v && v.value; // TODO: confirm this is the test condition
        });
    },
    message: "Array contains empty items"
};

// Some place else:
var arrayThatCannotContainEmptyValues = ko.observableArray([])
  .extend({ noEmptyValues: true });

尚不清楚 // TODO 行的测试内容,但我相信您可以弄清楚。

请注意,这仅在您修改实际数组时有效。由于 value 不可观察,因此不会触发上述示例中的更新。

我不确定这是否是您所期待的。如果你想为observableArray的每个对象添加验证,你可以这样做:

创建一个 captchaViewModel 函数并将 required 验证添加到 value 属性

var captchaViewModel = function(val) {
  this.value = ko.observable(val).extend({
    required: true
  });
 // other properties if any
}

然后将您的 viewModel 更改为:

var viewModel = {
  firstName: ko.observable().extend({ required: true }),
  lastName: ko.observable().extend({ required: true }),
  captcha: ko.observableArray([new captchaViewModel("test")]),

  submit: function() {
    if (viewModel.errors().length == 0) {
      alert('Thank you.');
    } else {
      alert('Please check your submission.');
      viewModel.errors.showAllMessages();
    }
  }
};

您还需要在 configuration 中添加 grouping 属性 并设置 deep: true.

ko.validation.configure({
   .......
   .......
  // "deep" indicates whether to walk the ViewModel (or object) recursively, 
  // or only walk first-level properties
  grouping: { deep: true }
});

Here's a fiddle for testing