Allow only numbers or letters in HTML inputs

What about forcing the user to type a number/letter in the input you want.

With just a bit of JavaScript we can control this what is the user typing int he input.

Allow only numbers:
(also dot and del)

function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode;
 
	if((charCode==46||charCode==8||charCode==45||charCode==47) ||(charCode >= 48 && charCode <= 57) ){
		return true;
	}
	else {
		return false;
	}		
}

And to use it in a input would be like this for example:

<input id="math"  type="text"  onkeypress="return isNumberKey(event);" />

Try it: How much is 20+10?

Allow only letters:
(also space, del, enter)

function isAlphaKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode;
	 if ((charCode==231 || charCode==199) || (charCode==241 || charCode==209) ||(charCode==8 || charCode==32) || ( (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) ) ) {
	 	return true;
	 }
	 else {
		 return false;
	 }
}

And to use it in a input would be like this for example:

<input id="name" type="text"  onkeypress="return isAlphaKey(event);"  />

Try it: Your name:

I know should be easier, but just wait a bit for HTML 5 that is going to make our life better. For sure ;)

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • FriendFeed
  • Meneame
  • Netvibes
  • Reddit
  • StumbleUpon
  • Tumblr
  • Wikio
  • RSS
  • email
  • PDF
  • Print

Related posts:

  1. mathCaptcha – Really simple captcha
  2. Check file extension in JavaScript
  3. jsCheckBox – Advanced select unselect checbox
  4. Google Maps full screen
  5. Change the CSS of your site with JavaScript

Leave a Reply

Follow me