Friday, February 24, 2012

A JavaScript Function that Allows Only Numbers

This little function will force users to type numbers, commas and periods only.
 function noAlpha(obj){
 reg = /[^0-9.,]/g;
 obj.value =  obj.value.replace(reg,"");
 }

reg = /[^0-9.,]/g is a regular expression that basically says: look for any numbers from 0 to 9, periods and commas globally.
Usage:
<input type=text onKeyUp='noAlpha(this)' onKeyPress='noAlpha(this)'>

Try it here.


Here is a version of this function that does not use regular expressions and allows numbers only.
function forceNumbers(obj) {
 if ( obj.value.length == 0)
  return;

 if (!parseInt(obj.value,10) && obj.value != 0)   {
  alert("Please enter a valid Number");
  obj.value = '';
  obj.focus();
  obj.select();
 }
 else {
  obj.value = '' + parseInt(obj.value,10);
 }
}

No comments:

Post a Comment