Last Updated: February 25, 2016
·
2.488K
· mo_roodi

Validating custom bindings with ko.validation

Knockout is a javascript library that allows simplifying dynamic javacript UIs by applying the MVVM pattern. The joy of knockout is that it really does make it easy to create dynamic UIs, with a simple binding syntax, and with the option of adding new custom bindings.

Knockout validation is a validation extension to Knockout which allows attaching validation rules to the view model.

The problem with knockout validation is that it requires a little work to get it working with custom bindings. By default knockout validation only works with the “value” and “checked” knockout bindings, which means there’s a little work involved in getting custom bindings to work with knockout validation. Fortunately knockout validation exposes the “makeBindingHandlerValidatable” which does just what it says on the tin.

In order to enable validation on a custom knockout binding first the binding needs to be registered with knockout, and then simple call “ko.validation.makeBindingHandlerValidatable(‘bindingName’)”.

I found the simplest way to deal with this is to do something like the following:

function registerCustomBindingValidation() {
    var args = Array.prototype.slice.call(arguments, 0);
    for ( var i = 0; i < args.length; i++ ) {
        ko.validation.makeBindingHandlerValidatable(args[i]);
    }
}

Then all we need to do is call the following once all the custom bindings have been registered with knockout:

registerCustomBindingValidation('customBinding1', 'customBinding2');

This will enable us to use both built in and custom validation rules on our custom binding.