javascriptknockout.jsmaskedinput

Is there masked input plugin for knockout.js using extenders?


I've seen this post - it shows one possible solution. But I would like to have a more elegant way of doing masked input.

It should also play nicely with knockout validation plugin (or maybe extending it).

Anyone know how is there similar project out there?


Solution

  • If you wanted to use the excellent Masked Input Plugin in Knockout, it's pretty easy to write a basic custom binding rather than an extender.

    ko.bindingHandlers.masked = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var mask = allBindingsAccessor().mask || {};
            $(element).mask(mask);
            ko.utils.registerEventHandler(element, 'focusout', function() {
                var observable = valueAccessor();
                observable($(element).val());
            });
        }, 
        update: function (element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).val(value);
        }
    };
    

    And then in your HTML:

    <input type="text" data-bind="masked: dateValue, mask: '99/99/9999'" />
    <input type="text" data-bind="masked: ssnValue, mask: '999-99-9999'" />
    

    And so on with various masks. This way, you can just put the mask right in your databinding, and it allows a ton of flexibility.