I have a small form where users enter a deposit in a dollar amount. This amount can be positive or negative. I am attempting to validate the form each time a key is pressed to prevent letters or characters from being entered by accident.
Consider the function below:
var deposit = document.getElementById("deposit");
deposit.onkeyup = function() {
var PATTERN = /\d$/;
if (!deposit.value.match(PATTERN)) {
deposit.value = deposit.value.replace(deposit.value.slice(-1), "");
}
}
This works fine and dandy if you only want your user to be able to enter numbers. Any other character will simply be erased. Where I am having trouble is coming up with a pattern that will work on the fly to match a positive or negative currency (without the dollar sign). Users need to be able to enter an optional negative sign, at least one number, followed by a decimal point, followed by 2 more numbers.
Example deposit amounts:
0.09
100.45
4032.34
-0.90
-54.56
-1353.00
Any help coming up with a pattern, or perhaps even a better method, would be greatly appreciated. Please let me know if more detail is needed.
You can use this validation pattern to match those number values.
^-?\d+\.\d{2}$