Restrict Numeric Input
jQuery
Only digits and point input
Max digits number after point
HTML
<h4>Digits Input</h4>
<div>Only digits input (maximum 2 digits after decimal point, decimal separator '.')</div>
<input id="Total" type="number" />
<div>Only digits input (maximum 3 digits after decimal point, decimal separator ',')</div>
<input id="Total2" type="number" />
<div>Only digits input (only positive natural numbers)</div>
<input id="Total3" type="number" />
JavaScript
DigitsInputHelper("#Total", 2, '.');
DigitsInputHelper("#Total2", 3, ',');
DigitsInputHelper("#TotalNotExist", 2, '.');
DigitsInputHelper("#Total3", 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 {
...