Conditional validation not working for anonymous Knockout validation rule
Asked Answered
P

1

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

Pomerania answered 30/1, 2013 at 10:15 Comment(2)
I still try to understand why your code is not working. Is model.IsCredentialsRequired a subscribable (observable or computed)?Firer
right,model.IsCredentialsRequired is computedPomerania
F
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/

Firer answered 30/1, 2013 at 10:35 Comment(2)
this worked,but what if i want a custom rule,i want answer in that case tooPomerania
I have updated the answer. In short: knockout-validation does not support onlyIf for anonymous rules. But it does for custom ones.Firer

© 2022 - 2024 — McMap. All rights reserved.