Max Koretskyi
Max Koretskyi

Reputation: 105547

custom validation rule is not triggered

I'm using the areSame rule from here:

ko.validation.rules['areSame'] = {
    getValue: function (o) {
        return (typeof o === 'function' ? o() : o);
    },
    validator: function (val, otherField) {
        return val === this.getValue(otherField);
    },
    message: 'The fields must have the same value'
};

And apply it like this:

this.confirm = ko.observable().extend({
    areSame: {
       params:this.password
    }
});

But it's never even triggered. I put debugger into validator function of the rule definition: validator: function (val, otherField) { debugger return val === this.getValue(otherField); }, however the flow never visits this point. What could be wrong?

EDIT:

The problem of not triggering validation is solved by calling ko.validation.registerExtenders();, however the rule doesn't work as expected. The problem is that the otherField variable, that is passed to validator, is the object {params:*observable here*}, where as the method getValue doesn't expect that as you can see from the source code. So either the source code is wrong or I defined the params for the rule in the wrong way. So which one?

Upvotes: 5

Views: 1931

Answers (1)

nemesv
nemesv

Reputation: 139788

Although it is not explicitly stated in the Wiki (it is in the sample code but not in the description) but

you need to call ko.validation.registerExtenders()

after you have defined your custom rules in order to register them:

ko.validation.rules['areSame'] = {
    getValue: function (o) {
        return (typeof o === 'function' ? o() : o);
    },
    validator: function (val, otherField) {
        return val === this.getValue(otherField);
    },
    message: 'The fields must have the same value'
};

ko.validation.registerExtenders();

In order to use your custom rule you don't need the "params syntax" so you can just write:

this.confirm = ko.observable().extend({
    areSame: this.password
});

If you want to use the "params syntax" you need to provide a custom error message property, otherwise the plugin does not correctly interprets the otherField argument :

this.confirm = ko.observable().extend({
    areSame: {
       params: this.password,
       message: 'a custom error message'
    }
});

Upvotes: 8

Related Questions