Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional validation not working for anonymous Knockout validation rule

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

like image 700
Cris Avatar asked Jan 30 '13 10:01

Cris


1 Answers

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/

like image 178
delixfe Avatar answered Sep 19 '22 20:09

delixfe