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.
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.
Share Improve this question asked Dec 16, 2016 at 14:10 midda25midda25 1602 gold badges2 silver badges12 bronze badges 2-
4
[-+]?\d+
accepts one or more digits that may or may not have a plus+
or minus-
in front of them. I don't follow what you mean about arrow keys, that's not really something regex interacts with – Patrick Haugh Commented Dec 16, 2016 at 14:13 -
0.125
,-.4
,0xbabe
,1e-23
,Infinity
,۸۹۸
etc - do you consider these to be "numbers"? – georg Commented Dec 16, 2016 at 14:51
1 Answer
Reset to default 5This 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.