
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.
0 comments:
Post a Comment