@joshdail
Posted
Nice job!
It is possible to restrict the input fields. I also had a really hard time finding info online on how to do that. I used a combination of regular expressions and JS string methods and it seems to work.
Here are the regex I used :
const regexNumeralsDecimalsOnly = /[^0-9.]/g
const regexNumeralsOnly = /[^0-9]/g
I couldn't figure out how to control the number of decimal places with regex, so after filtering with the regex I used string methods to filter down to only one decimal point and two decimal places. Then it immediately rewrites the value in the input field with the filtered value.
// First, filter the input value with regex, and escape out any invalid characters
const filteredInput = billInput.value.replace(regexNumeralsDecimalsOnly, "")
/* Force the input value to one decimal point and two decimal places at most
The ternary expression looks for a decimal. If it finds one, it slices the string
The first substring is the part before and including the decimal. The second part
is after the decimal. Any additional decimals in the second substring are escaped
out, and the length is limited to 2 characters */
const inputValue =
filteredInput.indexOf(".") >= 0
? filteredInput.substr(0, filteredInput.indexOf(".") + 1) +
filteredInput.substr(filteredInput.indexOf(".") + 1, 2).replace(".", "")
: filteredInput
// Immediately the value in the input field with the filtered value,
// preventing any invalid values from being entered
billInput.value = inputValue
Regexr.com is a good place to test out and learn about regex. Regex seems to be one of the best ways to filter input to what you want it to be.