I'm trying to set up a way to prevent inputs into certain fields in JavaScript. Most of my fields check against /^\d*$/.test(value) which will prevent any input from being typed in or shown that's non-numeric.
One particular field uses /^[\d.]*$/.test(value) which allows any number of digits and a decimal to be placed in as well.
My issue is that the decimal regex allows any number, or combination specifically, of decimals to be input. I'm trying to prevent inputs like "....", "13.24..36", ".2.2", etc.
Could anyone provide a regex that has to start with a number, end with a number, can have decimal or no decimal, and prevents two decimals being put together? (like .. <- preventing the second unless another number follows)
\d+(?:\.?\d+)? matches one or more digits and optionally a group of optionally a dot and some more digits
This still allows matches like .2 but you could check that the digits are not preceded by a dot: (?<!\.) and not followed by a dot: (?!\.)
The full pattern then becomes (?<!\.)\d+(?:\.?\d+)?(?!\.). Keep in mind that the negative lookbehind (?<!...) is not yet supported in every JavaScript environment. (Node.js and Chrome support it at present).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With