根据其他字段设置验证

时间:2013-09-16 18:27:22

标签: c# knockout.js

我有一个名为ReclaimTotalAmount的字段,它显示来自c#模型的值。

<div class="container-left">
Reclaim Total: <span data-bind='text: model.ReclaimTotalAmount'></span>
</div>

我还有一个显示字段总和值的字段:

 <div class="container-left">
    Countered Total:<span data-bind='text: model.CounteredTotalAmount'></span>
</div>

要获取CounteredTotalAmount,我使用以下

self.model.CounteredTotalAmount = ko.computed(function () {
    var SumCounterTotals = 0;

    for (var i = 0; i < self.model.CounterReclaimViewModels().length; i++) {
        SumCounterTotals += (
           parseFloat(self.model.CounterReclaimViewModels()[i].CounteredTimeAmount())
         + parseFloat(self.model.CounterReclaimViewModels()[i].CounteredMileAmount())
         + parseFloat(self.model.CounterReclaimViewModels()[i].CounteredAppurtenanceAmount())
     )
    }

所以我需要检查天气,反击总数大于ReclaimTotal。我试过这个: 我创建了一个扩展

 self.model.CounteredTotalAmount.extend({
    greaterThan: { params: self.model.ReclaimTotalAmount, message: "Car number high must be greater than the low." }
});

那么这就是函数

 ko.validation.rules['greaterThan'] = {
    validator: function (val, other) {
        if (val != null && val != "" && other != null) {
            var first = parseInt(val);
            var second = parseInt(ko.unwrap(other));
            if (!isNaN(first) && !isNaN(second)) {
                return first > second;
            }
        }
        return true;
    },
    message: 'Must be greater than or equal to the other value'
};

除验证外,一切正常。如果Countered Total大于Reclaim total,我将无法生成错误消息... 感谢

1 个答案:

答案 0 :(得分:1)

多个事情可能会出错,但是因为您还没有'仅发布一个完整的示例代码片段,您需要检查以下内容:

  1. 由于您要创建自定义验证程序,因此在首次使用之前需要先调用ko.validation.registerExtenders();
  2. KO .extend({ })返回扩展的observable,因此您需要使用结果覆盖现有属性:

    self.CounteredTotalAmount = self.CounteredTotalAmount.extend({
        greaterThan: {
           params: self.ReclaimTotalAmount,
           message: "Car number high must be greater than the low."
        }
    });
    
  3. 因为KO验证仅覆盖valuechecked绑定以自动显示错误消息。因此,您需要使用validationMessage绑定来显示错误,因为您在此处使用text绑定:

    <div class="container-left">
         Countered Total:<span data-bind='text: CounteredTotalAmount'></span>
         <span data-bind="validationMessage: CounteredTotalAmount"></span>
    </div>
    
  4. 这是一个有效的JSFiddle,其中包含代码的简化版本。