Skip to content

Validating A Computed Field

vongillern edited this page Jan 9, 2013 · 1 revision

Sometimes it is useful to validate a computed field. For the most part it works as expected, but because computed columns typically don't have any direct input fields that are bound to them, you'll need to explicitly add a validation message label for the computed field, because one will not automatically display like a field bound to an input field would.

<h2>Total Percent: <span data-bind="text: PercentSum"></span></h2>
<!-- because this is a computed column, validation errors WILL NOT automatically show -->
<span data-bind="validationMessage: PercentSum" class="validationMessage"></span>
viewModel.PercentSum = ko.computed(function() {
    var total = 0.0;
    for (var i = 0; i < viewModel.EmployeeAllocations().length; i++)
    {
        var entry = viewModel.EmployeeAllocations()[i];
        total += Number(entry.Percent());
    }
    return total;
});

ko.validation.rules['mustEqual'] = {
    validator: function (val, otherVal) {
        return val === otherVal;
    },
    message: 'The field must equal {0}'
};
ko.validation.registerExtenders();

viewModel.PercentSum.extend({ mustEqual: { params: 100, message: "Percentages must add to 100" } });
Clone this wiki locally