65.9K
CodeProject is changing. Read more.
Home

Validation of Numeric Values On keyPress Event USing Javascript

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL
viewsIcon

16373

It is better to use javascript functions for validating numeric values rather than Validation Controls.We can restrict a textbox to allow only

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);
}