Imx Fix in my experience
 
« prev next »

January 30, 2004 11:33 AM


It's 2004 already and just yesterday I wrote a JavaScript function to tell if a character passed into the function is an alpha-numeric character. One would think that after writing JavaScript for several years that the need for this check would have come up already (and furthermore that there would be a built in method in the language, but that's not the case).

I approached the problem by using ASCII character codes. If you have BBEdit, there's a pallette that shows all of those code next to their characters, so I used that to write an annoyingly long if statement with four "or" statements and two "and" statements imbedded in an or statement. Annoying, but effective. Here it is...

function alphaNumericCheck(theChar) {

	if ((theChar < 48) || (theChar > 122) || 
	   ((theChar > 57) && (theChar < 65)) || 
	   ((theChar > 90) && (theChar < 97))   ) {
		return false;
	} else {
		return true;
	}
}
To call the function, you would say something like...
<input type="button" name="foo" value="my button"
    onclick="alphaNumericCheck(this.value.charCodeAt(0))">
The part that says charCodeAt(0) will return the ASCII number for the character at the zeroth position in the string (the first character). The function will take that character and return "false" if it's not a number, a capital letter or a lowercase letter, and "true" if it is alphanumeric. Try it.