Only one minus symbol for negative numbers JS regex

Viewed 330

I have this code /^[-0-9\b]+(\.\d{0,2})?$/ for the positive and negative numbers validation

It's working fine for the negative numbers(for ex -12.34), but user can also type a few "-" symbols(ex: -12-3-4.12).

So how can I disable a possibility to type a multiple minus symbols?

2 Answers

You seem to be using the regex for liva validation. In these cases, the regex should comprise only optional parts, those that can match an empty string.

You can use

/^-?\d*\.?\d{0,2}$/

See the regex demo. Details:

  • ^ - start of a string
  • -? - an optional -
  • \d* - zero or more digits
  • \.? - an optional .
  • \d{0,2} - 0, 1 or 2 digits
  • $ - end of string.

[-0-9\b]+ Is making it possible to have one or more - characters.

Just change your regex to:

/^-?[0-9\b]+(\.\d{0,2})?$/

Here is the test:

https://regex101.com/r/fbMI7Z/1/

Related