Manually trigger knockout validation

Knockout Validation plugin makes it extremely easy to validate your model. You can use all the standard validation rules (like required, min/max length, etc), but you can also write custom rules. The plugin uses Knockout’s natural way of binding: the validation is triggered when the value of your attribute changes and the error messages are displayed if that attribute is not valid. In my recent project however we had a scenario, which was not naturally supported by the plugin – we needed a way to trigger the validation manually instead of on value change. Looking at plugin’s configuration, we could see a promising option – messagesOnModified. Unfortunately, setting this to false caused the error messages to be always displayed, instead of (as we expected) when we needed them. To solve this issue, we built our model in the following way:

We introduced an attribute, stating whether the validation is enabled or not. Now, we made use of cool feature of the validation plugin, namely the possibility to provide a boolean function saying whether the rule should be checked or not. The traditional way of attaching validation rules is

However, there is a longer syntax giving you more options.

Notice the onlyIf attribute, which we add to the rule object. It expects a predicate whether the rule should be executed or not. By using our custom predicate, we can disable all rules. This will disable all the rules. Note that you must add this to every rule you attach to your model. The question now is how to trigger the validation when we want it. If we take a look at the source code of the plugin, we can see the following code, which performs the validation on value change:

This code creates a computed variable, which always returns true. A computed variable is reevaluated when any of the observable variables used inside is changed. The more important thing here is the call to validateObservable() which  does the actual validation. Fortunately, this method is publicly available as ko.validation.validateObservable(). So, to trigger the validation manually it is enough to call this method for every attribute in our model, we wish to validate.

If you want to validate a group of attributes (or the entire model), you can use the plugin’s helper function, called