Click here to Skip to main content
Click here to Skip to main content

Using Observable And Computed for Validation in Knockout

, 4 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.

Introduction

If we check https://github.com/Knockout-Contrib/Knockout-Validation

We will find out how the knockouts basic and custom validations work. But some time we may want to use one of the observables value to take part in validation process. To do so we have to use a little trick.

Background

For quick review check http://jsfiddle.net/ZfUWH/

Now let’s say we have two observables at the view model, first number and second number. And the validator should work for the validation where first number need to be less than the second number (first number < second number).

So we have to pass first numbers value to the second numbers validator rules, for validation.

Using the code

Let’s say we made a custom validator rule "isLargerThan" for the validation, now we are gona use it in secondNumber observable like this.

Here using ko.computed is important, because it is working with the observable firstNumber.

If you don't use ko.computed, the custom validator would become a regular static validator, where changeable firstNumber values would not be considered in validation process, every time when it value changes

/*fields*/
self.firstNumber = ko.observable('').extend({ required: true, min: 0, digit: true});
self.secondNumber = ko.observable('').extend({
    required: true,
    min: 0,
    digit: true,
    isLargerThan: ko.computed(function () {  //custom validation
        return self.firstNumber();          //assigning observable
    })
});

Here is our custom validator rule,

Where reassigning otherVal = otherVal() is important, as we sanded ko.computed function, and value is stored inside the function itself.

/*Validation: 1*/
ko.validation.rules['isLargerThan'] = {
    validator: function (val, otherVal) {
        /*important to use otherValue(), because ko.computed returns a function,
        and the value is inside that function*/
        otherVal = otherVal();                
        return parseFloat(val) > parseFloat(otherVal);
    },
    message: 'This need to be larger than the First Number '
};
ko.validation.registerExtenders();

If we want to use more observables to for validation, we just only need to use more of them at the return session of ko.computed with property names, as we did in here

self.thirdNumber = ko.observable('').extend({
    required: true,
    min: 0,
    digit: true,
    isBetween: ko.computed(function () {
        return {                            //assigning multiple observables
            firstNumber: self.firstNumber(),
            secondNumber: self.secondNumber()
        };
    })
});


/*Validation: 2*/
ko.validation.rules['isBetween'] = {
    validator: function (val, otherVal) {
        /*important to use otherValue(), because ko.computed returns a function,
        and the value is inside that function*/
        otherVal = otherVal();
        return parseFloat(val) >= parseFloat(otherVal.firstNumber)
            && parseFloat(val) <= parseFloat(otherVal.secondNumber);
    },
    message: 'This need to be between than the First Number and Second number'
};
ko.validation.registerExtenders();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 4 Jul 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid