Reputation: 718
I have a field called ReclaimTotalAmount that displays a value from a c# model.
<div class="container-left">
Reclaim Total: <span data-bind='text: model.ReclaimTotalAmount'></span>
</div>
And I also have a field that displays the value of the Sum of fields:
<div class="container-left">
Countered Total:<span data-bind='text: model.CounteredTotalAmount'></span>
</div>
To get the CounteredTotalAmount I use the following
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())
)
}
So I need to check weather the Countered total is greater than the ReclaimTotal. I tried this: I created an extension
self.model.CounteredTotalAmount.extend({
greaterThan: { params: self.model.ReclaimTotalAmount, message: "Car number high must be greater than the low." }
});
then this is the function
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'
};
everything works except the validation. I am not able to generate an error message if the Countered Total is greater than the Reclaim total... Thanks
Upvotes: 1
Views: 602
Reputation: 139758
Multiple things could go wrong, but because you haven't' posted a complete example only code fragments you need to check the following things:
ko.validation.registerExtenders();
before you want to use it for the first time.the KO .extend({ })
returns the extended observable so you need to override the existing property with the result:
self.CounteredTotalAmount = self.CounteredTotalAmount.extend({
greaterThan: {
params: self.ReclaimTotalAmount,
message: "Car number high must be greater than the low."
}
});
Because KO validation only overrides the value
and checked
binding to automatically display the error message. So you need to use the validationMessage
binding to display your error because you are using the text
binding here:
<div class="container-left">
Countered Total:<span data-bind='text: CounteredTotalAmount'></span>
<span data-bind="validationMessage: CounteredTotalAmount"></span>
</div>
Here is a working JSFiddle with the simplified version of your code.
Upvotes: 1