Reputation: 1576
I am now using this regex,
Regex rg = new Regex(@"\d{1,16}\.?|\d{0,16}\.\d{1,3}");
to validate the decimal values entered into a Textbox. It works fine. But it allows a user to enter decimal values together with non-numeric characters like 2.a
or 2\
.
I believe that wrong portion is here \.?
. I have used ?
so it accepts alphabetical values?
I have tried something like \.[0-9]?
but it's not working.
Below are valid and invalid values:
There might be duplicate questions on SO. But valid regex tokens vary by implementation. That's why I asked a new question here. Any help will be much appreciated!
Upvotes: 0
Views: 3946
Reputation: 43023
You can use that regex:
^\d{1,16}(\.\d{1,4})?$
It will validate first between 1 and 16 digits an optional dot and 1 to 4 digits.
If you want to always have dot, you should use:
^\d{1,16}((\.\d{1,4})|(\.))?$
Upvotes: 2
Reputation: 654
The regex
^\d{1,16}(\.\d{1,4})?$
works fine, if you want to recognize if only on point you can add
^(\d{1,16})|(\d{1,16}\.{1}\d{0,4})|(\d{1,16}\.{1})$
It's not as elegant as the other but works in the scenarios you posted.
Upvotes: 1