DigitsInputHelper

by Ivan Gerasimenko

HTML

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css">
<div class="form-group">
    <label>Money xxx.xx</label>
    <input type='text' id='money' />
</div>
<div class="form-group">
    <label>Length xxx,xxxx</label>
    <input type='text' id='length' />
</div>
<div class="form-group">
    <label>Integer xx</label>
    <input type='text' id='integer' />
</div>

JavaScript

DigitsInputHelper('#money', 2, '.');
DigitsInputHelper('#length', 4, ',');
DigitsInputHelper('#integer', 0);

/* Allows only digits and one point input, restrics length of mantissa */
function DigitsInputHelper(inputSelector, mantissaLength, decimalSeparator) {
    if ($(inputSelector).length > 0) {
        BindKeyPressUpEvents();
        return $(inputSelector);
    } else {
        return [];
    }

    var valueBeforeKeyEnter;

    function BindKeyPressUpEvents() {
        $(inputSelector).keypress(function (e) {
            var code = e.keyCode || e.which;

            if (GetNumberOfDigitsAfterPoint($(this).val()) <= mantissaLength)
                valueBeforeKeyEnter = $(this).val();

            // allowed key codes
            if (code == 8
                || code == 9
                /*|| code == 37 // '%' */ 
                /*|| code == 39 // ''' */)
                return;

            // only digits
            if (mantissaLength == 0 && (code < 48 || code > 57)) {
                e.preventDefault();
            }
            // NOT allowed key codes
            if ((code != 44 || $(this).val().indexOf(decimalSeparator) != -1
                || decimalSeparator != ',')
                && (code != 46 || $(this).val().indexOf(decimalSeparator) != -1
                || decimalSeparator != '.')
                && (code < 48 || code > 57)) {                 // not number
                e.preventDefault();
            }
        });
        $(inputSelector).keyup(function (e) {
            var inputValue = $(this).val();

            if (GetNumberOfDigitsAfterPoint($(this).val()) > mantissaLength)
                $(this).val(valueBeforeKeyEnter);
        });
    }

    function GetNumberOfDigitsAfterPoint(number) {
        var patternDigitsAfterDot = 
            new RegExp("\\" + decimalSeparator +"\\d*");

        if (number.indexOf(decimalSeparator) == -1) {
            return 0;
        } else {
            return...