Every javascript programmer comes across the client side validations where he has to restrict user inputs depending on the requirement.
Yesterday i came along an issue where i required only numeric input for the textbox.
So i wrote a script which allowed me to enter only digits in a text field.
Here’s my script snippet.
<input onkeypress="return validateNumericCharacter();" name="zipCode" size="5" type="text" />
The HTML code calls the validateNumericCharacter function on keypress event.
validateNumericCharacter=function() { var k = event.keyCode ? event.keyCode :event.charCode ? event.charCode : event.which; return /^(\d)$/.test(String.fromCharCode(k)); }
The javascript’s first lineĀ identifies the keyCode and then forms a character out of it.
I then compares the character and finds out whether it is a digit or not using Regex.
The Quirk
The script works fine as in, it does not allow me to enter characters other than digits.
But there is a quirk to the script, to my surprise when i entered 313001 in the textbox and tried to select the whole text using SHIFT + HOME, it didn’t work. It did not select the whole code.
I tried a different technique and selected the zipcode using mouse and presses DEL key, and again nothing happened.
And even i was not able to delete the zipcode by selecting it with mouse and hit BACKSPACE key.
This can be seen live on many websites. One example is makemytrip.co.in’s registration page. When we try to fill mobile number field we can see the same phenomena mentioned in this post.
I was left wondering why its happening?
Can someone suggest why that was happening? Did i make any mistake in my javascript snippet.



























































