Wednesday, August 21, 2013

Javascript Phone Number Knockout Binding

Hey, all...

Over the years, I must have written a dozen phone number textboxes. Unfortunately I never save the code. I get to play with Knockoutjs at my new job so I figured I'd give the number textbox another shot.



    ko.bindingHandlers.phoneNumber = {
        formatNumber: function (box) {
            var box = $(box);
            var value = box.data("value");
            if (value.length <= 10) {
                value = value.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1) $2-$3');
            } else {
                value = box.data("value").replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)(\d+)/, '($1) $2-$3 x$4');
            }
            $(box).val(value);
        },
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var _this = ko.bindingHandlers.phoneNumber;
            var textbox = $(element);
            //function formatNumber(box) {
            //}
            textbox.keydown(function (e) {
                // allow cut/copy/paste
                if (e.ctrlKey && (e.which === 67 || e.which === 86|| e.which === 88)) {
                    return;
                }
                // allow delete and backspace
                if (e.which === 8 || e.which === 46) {
                    return;
                }
                // Ensure that a number was pushed
                if (e.shiftKey || !((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105))) {
                    e.preventDefault();
                }
            });
            textbox.focusin(function (e) {
                var value = textbox.data("value") || "";
                textbox.val(value);
            });
            textbox.focusout(function (e) {
                var value = textbox.val().replace(/[^0-9]+/g, '');
                textbox.data("value", value);
                _this.formatNumber(this);
                valueAccessor()(value);
            });
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var _this = ko.bindingHandlers.phoneNumber;
            var textbox = $(element);
            var value = valueAccessor()().replace(/[^0-9]+/g, '');
            textbox.data("value", value);
            _this.formatNumber(textbox);

        }
    }