Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

A JavaScript function to allow numbers only

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:

If you want to disallow commas and periods, you can easily modify the regular expression into the following:
reg = /[^0-9]/g;

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