RSS
Facebook
Twitter

Saturday 15 September 2012

How to validate numbers using JavaScript

javascript-check-numberThere are many times in the recent past where I have had to validate user input before it goes into the database. I have tackled this problem mainly with server side validation, which works pretty well. This though, was not as responsive as my clients want their systems to be. I therefore had to resort to adding client side validation, in addition to the server side validations already in place.
ECMA Script, aka JavaScript is ideal for these tasks with its main benefit being instant user feedback, either with a message, or by auto-correcting the input. The code below does the latter for numbers, and can be used to verify fields that need prices, phone numbers and the like.

Example usage

<input type="text" 
onblur="extractNumber(this,2,true);" 
onkeyup="extractNumber(this,2,true);" 
onkeypress="return blockNonNumbers(this, event, true, true);" />
blockNonNumbers takes the following arguments
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
extractNumber takes the following arguments
function extractNumber(obj, decimalPlaces, allowNegative)

How the above example works

1. Character-by-character validation
The point of validating each character as it’s entered is to prevent unwanted characters from showing up in the first place (as opposed to showing up then being removed). Character validation is accomplished by using function blockNonNumbers with the input’s onkeypress event, which will return either true or false. A return value of false means the last character entered will not show up.
2. Entire value validation
Sometimes a single character isn’t enough to determine if the entire value follows a certain format. Therefore, the example on this page uses function extractNumber in the onkeyup and onblur events.
Event onkeyup is called after the character has been entered. This means that in some situations (like verifying the number of decimal places), you may see the character appear, then disappear.
Event onblur is called when focus leaves the text box. This will catch attempts at copy/pasting.
These are the events that were chosen for this example, but sometimes it will suffice to only have one event fired. It depends on the needs of the formatting.

More examples and integration

Download the file below to get more examples of how the script can work for you!

0 comments:

Post a Comment