midda25
midda25

Reputation: 160

Regex for negative and positive numbers

I need a regex for an input field to allow negative and positive numbers and no alphabet/special characters. I have seen other people achieve this but they allow the minus sign at any point in the string whereas I only want to allow the minus sign at the beginning of the string.

Note: I want to allow the user to use the arrow, del, home keys etc.

Upvotes: 2

Views: 20509

Answers (1)

Mattasse
Mattasse

Reputation: 1161

This the regex to get positive and negative numbers :

^-?\d+$

If you want decimal numbers you can use this :

^-?\d+(\.\d{1,2})?$

The parameter {1,2} at the end is for precision of your decimal number.

Upvotes: 5

Related Questions