1

我对 observablearray 元素的验证规则有疑问。我正在使用自定义消息模板来显示错误,问题是当错误出现时它不会显示,但是,我可以在相关字段中看到“*”。以下是我的模型:

function ViewModel(item) {
var parse = JSON.parse(item.d);
var self = this;
this.ID = ko.observable(parse.ID).extend({ required: { params: true, message: "ID is required" }});
this.Name = ko.observable(parse.Name);
this.WeeklyData = ko.observableArray([]);
var records = $.map(parse.WeeklyData, function (data) { return new Data(data) });
this.WeeklyData(records);
}

var Data = function (data) {
this.Val = ko.observable(data).extend({
    min: { params: 0, message: "Invalid Minimum Value" },
    max: { params: 168, message: "Invalid Maximum Value" }   
});

这是我正在使用的验证配置:

    // enable validation
    ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: false,
    insertMessages: true,
    parseInputAttributes: false,
    messageTemplate: "customMessageTemplate",
    grouping: { deep: true }
    });
    ko.validation.init();

我的任何自定义消息模板都是这样的:

   <script id="customMessageTemplate" type="text/html">
      <em class="errorMsg" data-bind='visible: !field.isValid()'>*</em>
   </script>

   <ul data-bind="foreach: Errors">
     <li class="errorMsg" data-bind="text: $data"></li>
   </ul>  

使用此实现,我在自定义模板中看不到验证消息。但是如果我删除配置 deep: true,它不会验证 observable 数组元素,而是另一个 observable(ID),然后消息会正确显示。

我对此感到非常困惑并且有点卡住了,如果有人可以提供帮助,我将不胜感激/

提前致谢。

4

2 回答 2

0

What i understand from your question is that you are trying to validate your observableArray entries, so that if any entry in your WeeklyData observableArray fails the following condition:

arrayEntry % 15 === 0

you want to show error message. If this is the case, than the following custom validator can do the job for you :

var fminIncrements = function (valueArray) {
  var check = true;    
  ko.utils.arrayFirst(valueArray, function(value){
        if(parseInt(value, 10) % 15 !== 0)
        {
          check = false;
          return true;
        }
     }); 
  return check;
};

And you have to apply this validator on the observableArray (no need to set validation on individual entries of the array). This validator takes array as input and validate its each entry, if any one entry fails the validation it will retrun false and than you will see the error message.

Your viewmodel looks like :

function viewModel() { 
    var self = this;

    self.WeeklyData = ko.observableArray([
      15, 
      40
    ]).extend({ 
        validation: {
          validator: fminIncrements,
          message: "use 15 min increments" 
        }
    });


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

And here is the working fiddle.

于 2013-04-05T09:55:10.300 回答
0

单个项目未显示消息-仅在摘要中-您如何在单个文本框中指定消息?

于 2013-05-17T14:02:53.623 回答