There are several reasons we need to make numeric only textbox in our web form and here is how to restrict textbox input. Actually, it is not only for numeric textbox validation. It is also useful for many things. For example: textbox for email, phone number, Fax number and so on.


Input :
Key Code :

    
function isValid(event)
{
	// backspace = 8
	// shift  = 16
	// left arrow = 37
	// right arrow = 39
	var keyCode = (event.which) ? event.which : event.keyCode;
	var validCodes = new Array(8,16,37,39);
	var i = validCodes.length;

	//Just for displaying keycode
	document.getElementById('txtDisplay').value = keyCode;

	if (keyCode < 48 || keyCode > 57){
		while (i--) {
		  if (validCodes[i] === keyCode) {
				return true;
			}
		}
		event.preventDefault? event.preventDefault() : event.returnValue = false;
	}
	else{
      return true;
    }
}
     Test Here : <input id="txtInput" onkeypress="isValid(event)" type="text" />
     Key Code  : <input id="txtDisplay" readonly="readonly" type="text" />



author's photo

Author : Blue Cloud

Just a normal software developer who love to write code. Developing professional software since 1999. After working in the software industry for many years, I've started my own website to share knowledges and experiences.

COMMENTS
blog comments powered by Disqus