Categories
JavaScript

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:

 

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:

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 😉