Conditional validation not working for anonymous Knockout validation rule

Cris picture Cris · Jan 30, 2013 · Viewed 9.5k times · Source

I have following attributes in my viewmodel which use knockout validation,one of them is custom validation to check password match.

model.Password = ko.observable()
                  .extend({ required: { message: "Password is required.", 
                        params: true,
                        onlyIf: function () { return model.IsCredentialsRequired(); }}
                    });


model.ConfirmPassword = ko.observable().
                        extend({ validation: { validator: mustEqual,
                        message: 'Passwords do not match.',
                        params: model.Password,               
                        onlyIf: function () { return model.IsCredentialsRequired(); } }
                    });

code for custom validation function

var mustEqual = function (val, other) {
                return val == other();
            };

I found that OnlyIf condition is working fine for model.Password depending on model.IsCredentialsRequired() but its not working for model.ConfirmPassword,Can somebody help me why this is happening?Is there any another way by which i can use conditional validation for custom rules?

Thanks in advance

Answer

delixfe picture delixfe · Jan 30, 2013

knockout-validation does currently not support 'onlyIf' for anonymous rules. But it is supported for custom rules. Therefore you can create a custom rule and use onlyIf with that:

ko.validation.rules['confirmPasswordMatches'] = {
    validator: function (val, params) {
        var otherValue = params;
        return val === ko.validation.utils.getValue(otherValue);
    },
    message: 'Passwords do not match.',
};
ko.validation.registerExtenders();

function ViewModel() {
    var self = this;

    self.IsCredentialsRequired = ko.observable(true);

    self.Password = ko.observable()
        .extend({
            required: {
                message: "Password is required.",
                params: true,
                onlyIf: self.IsCredentialsRequired
            }
    });

    self.ConfirmPassword = ko.observable().
    extend({
            confirmPasswordMatches: {
            params: self.Password,
            onlyIf: self.IsCredentialsRequired
        }
    });

}

Fiddle: http://jsfiddle.net/delixfe/mFAEx/