Search code examples
javascriptknockout.jsknockout-validation

Knockout Validation - have input validate some other field


I'm using knockout validation and trying to accomplish what should be a simple use case.

I want an input to be bound to a certain field, but validate a different one. Something like this:

<input type="text" data-bind="validationElement: referrerId, value: referrerName" />  

But it seems to always (correctly) show validation errors for referrerName instead of referrerId. Is there any way to get this to work?

Basically I want this fiddle:

http://jsfiddle.net/W3pQt/1/

to show an error for referrerId (which in the fiddle is always empty).


Solution

  • http://jsfiddle.net/W3pQt/3/

    I made a custom validator, because I couldn't figure out how to do it without one.

    ko.validation.rules['dependsOn'] = {
        validator: function (val, otherVal) {
            return typeof otherVal() !== "undefined";
        },
        message: 'Referrer Id must have a value: {0}'
    };
    
    ko.validation.registerExtenders();
    

    ...

    this.referrerName.extend({ dependsOn: this.referrerId });
    

    Don't get hung up on the name 'dependsOn' which is dumb. Naming things is hard.