Validation of Numeric Values On keyPress Event USing Javascript
It is better to use javascript functions for validating numeric values rather than Validation Controls.
We can restrict a textbox to allow only numeric values using javascript functions.
These function will block the user to enter non numeric values by using keycode of each key on keyboard so that user can't enter illegal values into the respective fields.
function blockNonNumbers(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);
}
Revision number 1, Saturday, February 27, 2010 7:39:38 AM by sajithms85
This is not the most up to date version of this article. The most recent version can be found here.
You must Login to comment.
|
Mon, Apr 19, 2010 3:12 AM
by wisemikky
|
i would like to know the parameters to pass to this function
|