Search code examples
knockout.jsknockout-validation

Aggregate multiple max KO extend validations


I am using ko extend validation to validate, Trying to do something like follows. ko.extend does not support multiple bindings for same type (max in this case) and it only adds first rule. Is there a way to conditionally pass the params with a function? or my only way out is writing a custom validation?

         myModel.prop2.extend({
            max: {
                onlyIf: function () {

                    var test = myModel.prop1() != undefined &&
                        myModel.prop1() !== "Percentage";
                    return test;
                },
                params: 100000
            }
        }).extend({
            max: {
                onlyIf: function() {
                    return myModel.prop1() != undefined &&
                        myModel.prop1() === "Percentage";
                },
                params: 100
            }
        });

Solution

  • Found a solution,

    .extend({
                validation: [{
                    validator: function (val, someOtherVal) {
                        if (myModel.prop1()() !== "Percentage") {
                            return val < someOtherVal;
                        }
                        return true;
                    },
                    message: "Too big!!!!",
                    params: 100000
                }]
            })