12

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

Cris
  • 12,799
  • 5
  • 35
  • 50

1 Answers1

18

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/

delixfe
  • 2,471
  • 1
  • 21
  • 35
  • 1
    this worked,but what if i want a custom rule,i want answer in that case too – Cris Jan 30 '13 at 11:18
  • 3
    I have updated the answer. In short: knockout-validation does not support onlyIf for anonymous rules. But it does for custom ones. – delixfe Jan 30 '13 at 11:43