Onkeypress Javascript Numeric and Decimal Validation


Step : 1
Form Input Text Box:



Step : 2
Now place javascript validation code in the head or external javascript file like validation.js


function digits(obj, e, allowDecimal, allowNegative)
{
var key;
var isCtrl = false;
var keychar;
var reg;

if(window.event) {
key = e.keyCode;
isCtrl = window.event.ctrlKey
}
else if(e.which) {
key = e.which;
isCtrl = e.ctrlKey;
}

if (isNaN(key)) return true;

keychar = String.fromCharCode(key);

// check for backspace or delete, or if Ctrl was pressed
if (key == 8 || isCtrl)
{
return true;
}

reg = /\d/;
var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

return isFirstN || isFirstD || reg.test(keychar);
}