3

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)

3
  • 2
    And you aren't using input type="number" because....? Also, if you insist on regex for some reason, /^\d*(?:\.\d+)?$/ Commented Mar 18, 2020 at 19:35
  • Jared's comment is the correct universal way of checking for a decimal value. The only thing that can fail is if a user use comma instead of dot (Europeans do that). Commented Mar 18, 2020 at 22:10
  • I'm not using number input fields because they include the incremental arrows and I don't want to have to go through the trouble of altering the core CSS file to remove them. The idea is to make multiple listeners in Js that prevent any sort of improper input from being typed at all to help prevent validations at a later point. Everything works except finding a regex that allows that one field to have decimals put in but only in the right manner Commented Mar 19, 2020 at 18:02

1 Answer 1

3

\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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.