We have witnessed the wonders of JavaScript and its ability to ensure that our forms are properly filled before submission. But it gets so laborious to type and modify and update form validation scripts for every for in every application. Take heart! Upon reading and applying the methods in this article, you will never again have to worry about client-side validation! Hazzah!
Universal Form Validation - Pick a Number, Any Number! (Page 4 of 5 )
Now, to ensure numeric data types, we could just rely on post-submission server-side checking. You can refer to the article Easy Error Management for the perfect method (‘IsTrulyNumeric’) of doing that.
While that is good, and we still want to use such checking just in case, we don’t want to deter the user from finishing the form. You see, if we give them an error message after they’ve gone through the trouble of finishing the form, then forcing them to go back and change it, chances are that they’ll click the lovely grey ‘x’ in the top right corner of the screen.
The most effective way I’ve found yet is using JavaScript to traps keystrokes as they’re entered, and only allow them if they’re numeric. Simply add this to each field that’s only accepts numbers:
onkeypress
="return integersOnly( event )"
And here’s the function itself:
function integersOnly
(e) { e = (e) ? e : event; var charCode = (e.intCode) ? e.intCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0)); if (intCode > 31 && (intCode < 48 || intCode > 57)) { alert("Numbers only please!."); return false; } return true; }
So this is pretty simple, and is stops letters from ending up where they don’t belong! This function can be modified to allow further characters, such as ‘.’ or ‘-‘, or whatever else you need it for!
You may be inclined to remove the alert, but I wouldn’t. You see, users get fairly frustrated when it seems that their keyboard has inexplicably failed to enter the key they know they just depressed with their finger. This in turn may lead to them angrily displaying that very finger to you.
It’s just best to let them know what’s going on. Trust me.