Saturday, March 03, 2012

KnockoutJS validation (and more)

If earn money doing web development and haven’t yet heard of KnockoutJS – you should probably find out sooner than later. It’s a powerful and yet surprisingly intuitive MVVM framework implemented in pure Java Script (meaning - it will work in any browser!). The author’s is a good place to start and when you are ready for a deeper dive – check the
While building my first form with Knockout, which quickly got over-engineered beyond the concepts described in the documentation, I found that the ability to add some validation or allow user to confirm the action is sorely missed. gave me a good start in a right direction and I ended up with this observable:

ko.smartObservable = function (initialValue, functions) {
var _temp = initialValue;
var _value = ko.observable(initialValue);

var result = ko.computed({
read: function () { return _value(); },
write: function (newValue) {
var shouldUpdate = true;
_temp = newValue;
if (functions) {
for (var i = 0; i < functions.length; i++) {
if (shouldUpdate && typeof (functions[i]) == "function")
shouldUpdate = functions[i](newValue, this.parent);
if (!shouldUpdate) break;
if (shouldUpdate) {
if (_temp !== _value()) _value(_temp);
else {
_temp = _value();
return result;

You need to supply an optional list of functions, each accepting a single value parameter and returning true or false, and the observable will execute them one after another until the list is over or until one of the functions returns false.

This is a working code (the example is based on a simple tutorial model):

This observable works perfectly with a brilliant Matthew Schnikel’s dirty flag extender – combined together they will arm you with really powerful input fields.

But the best thing about KnockoutJS is that it made me rethink my disposition towards Java Script. How Melvin Udall would put it:


No comments:

© 2008-2013 Michael Goldobin. All rights reserved