Tag Archives: KnockoutJS

My time number format knockout binding

I made this binding so that I could correct the time number format written by a user (hh:mm). A way to make inputing time values easier. The binding will create time strings from one, two, three and four values. It vill also correct any mistyped characters in between hour and minutes

ko.bindingHandlers.timebox = {
  init: function(element, valueAccessor) {
    var allNumbers = /^\d{4}$/;
    var oneNumber = /^\d$/;
    var twoNumbers = /^\d{2}$/;
    var threeNumbers = /^\d{3}$/;
    var correct = /^\d{2}.\d{2}$/;
    var observable = valueAccessor();
    var formatted = ko.computed({
      read: function (key) {
        return observable();
      },
      write: function (value) {
        if(correct.test(value)){
          value = value.substring(0,2) + ':' + value.substring(3);
        }
        else if(allNumbers.test(value)) {
          value = value.substring(0,2) + ':' + value.substring(2);
        }
        else if(threeNumbers.test(value)) {
          value = '0' + value.substring(0,1) + ':' + value.substring(1);
        }
        else if(oneNumber.test(value)) {
          value = '0' + value + ':00';
        }
        else if(twoNumbers.test(value)) {
          value = value + ':00';
        }
        else {
          alert("Wrong time format specified (hh:mm)");
          value = '';
        }
        observable(value); // Write to underlying storage 
      },
      disposeWhenNodeIsRemoved: element                
    });
 
    //apply the actual value binding with our new computed
    ko.applyBindingsToNode(element, { value: formatted });
  }        
};

Using it is really easy. Just replace ‘value’ with ‘timebox’ like this:

<input id="my_id" type="text" data-bind="timebox:my_observable"/>

Tested on OSX 10.7.5, Chrome 37.0.2062.94, KnockoutJS 3.1.0