Using KO Validation Only If Effectively

Written by Adit Shah on September 07, 2016

Using KO Validation Only If Effectively_image

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

It also has a validation library that has built-in methods for validating user input.

Let’s say you want to validate an observable only if a certain condition is satisfied.  We have an onlyIf property for that in ko.validation plugin.



        required: {

            message: “Value is required”,

            onlyIf: function () { return (self.Observable2() === false); }



Now, the condition may or may not depend on the same class’ property.  The key thing is it must be accessible from the extend method. Let’s assume we have the following ViewModel.


var ViewModel = function() {

    var self = this; 

    self.UserModel = {

        Email : ko.observable(),

        Password: ko.observable(),

        ChooseToRecieveMessages: ko.observable(),

        Phone: ko.observable()




Now we want Phone to be required only if ChooseToRecieveMessages is set to true. We cannot extend Phone in the UserModel directly as the declaration of ViewModel is not yet complete. The browser will throw an undefined javascript error. If UserModel was a function definition, then it is a different thing, but in this case, it’s not.

So we implement our code as follows.


$(document).ready(function() {

    var vm = new ViewModel();


       required: {

           message: “Phone is required”,

           onlyIf: function() {

               return (vm.UserModel.ChooseToRecieveMessages() == true);








We extend the observable just before applying bindings.

This technique will ensure that our ViewModel is declared before we use its properties. It will also be very helpful if we have more than one ViewModel and onlyIf depends on properties from both ViewModels.

Kaira Software Pvt. Ltd. Is One Of The Leading Enterprise Web & Mobile Apps Development Company In India With An Industry Experience Of More Than A Decade.

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha *