HTML using input pattern for input of integer from -99 to 99 (optional negative mark)

Viewed 44

I would like to allow my input box in HTML to receive only integers from -99 to 99,
but if I use pattern="[-][0-9][0-9]{2,3}" or [-0-9]|[0-9]{2,3} or anything similar it allows the user to place from -99 too 999.

How can I make this negative sign - only optionally at the front of the introduced digit?
I.e. either the user will use it at the beginning of the introduced value, and if not, max 2 digits in a whole (above 0) value.

1 Answers

First, you could use type="number" with min and max attributes, which would probably be the best option.

Alternatively, the right pattern is -?[0-9]{1,2}.

  • - is a literal minus sign (no need to enclose it in brackets)
  • ? means the previous atom (in this case the minus sign) is optional
  • [0-9]{1,2} means one or two digits, so anything from 0 to 99 (including 00, 01…)
Related