jhanink
8/23/2013 - 4:51 AM

restrict input to currency number format

restrict input to currency number format

directives.directive('restrictInputFormatCurrency', ['MacAppUtils', function(MacAppUtils)
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{
    return {
        link: function(scope, elm, attrs) {
            elm.keypress(function (event){
                //var num = MacAppUtils.normalizeFloat(elm.val());
                var fractionToken = MacAppUtils.getFractionSeparator();
                var a = elm.val().split(fractionToken);

                var key = MacAppUtils.getKeyCode(event);
                var charFromKeyCode = String.fromCharCode(key)

                gLog.noop("key ["+key+"] charFromKeyCode ["+charFromKeyCode+"]");

                var selectStart = elm[0].selectionStart;
                var selectEnd = elm[0].selectionEnd;
                var hasSelection = selectStart != selectEnd;

                // input formats are localized

                // allow numbers, backspace (8), tab (9), left arrow (37), right arrow (39), decimal (46), comma (44)
                var isAllowedControlCharacter = (key === 8 || key === 9 || key === 37 || key === 38 || key === 39 || key === 40);
                var isAllowedInputCharacter = ((key >= 48 && key <=57) || fractionToken == charFromKeyCode/*key === 46 || key === 44*/);

                // check fractional component block more than 2 decimal digits
                if (a.length > 1 && a[1].length > 1) {
                    if (!hasSelection && !isAllowedControlCharacter) {
                        event.preventDefault();
                        return false;
                    }
                }

                // block disallowed characters
                if (!isAllowedInputCharacter && !isAllowedControlCharacter) {
                    event.preventDefault();
                    return false;
                }
                return true;
            });
        }
    };
}]);