Reputation: 1566
I am using this regex to validate input strings as decimal
values in Textbox.
^\d{1,16}((\.\d{1,4})|(\.))?$
Now I want to allow negative decimal
values. I have found many similar questions on SO. And I tried something like these:
/^-?
, (\+|-)?
, \.\d{1,4}\-
but not working.
The reason I asked a new question here because I am using Textbox TextChanged
event and I need to check each character entered into the Textbox.
So the first character, minus(-) sign, should be valid
Positive Values
1
1.
1.1
1.1111
Negative Values
-
-1
-1.
-1.1
-1.1111
The Regex that I have above validate for positive values. How can I modify my Regex to allow negative values? Any help will be very much appreciated.
Upvotes: 11
Views: 25279
Reputation: 72855
You need to escape the minus sign because -
is a special character.
Try (\+|\-)?
(note the backslash).
Edit: Not sure if this will do what you want, but it's a lot simpler:
^\-?\d*\.?\d*$
Will match any decimal (1 to infinite chars on either side of a decimal, with or without a -). More details here: http://regex101.com/r/rP7cG2
Upvotes: 14