Reputation: 26424
I'm looking for a regular expression that would validate a non-negative decimal (.NET type), i.e. if a non-negative value can be parsed using decimal.Parse(...)
, it should be considered valid. Otherwise invalid.
I'm okay if it fails the 28-29 significant digits validation - relying on user's sanity here - and then we have another validation layer that would catch it anyway.
Here is what I came up with:
^(?:[1-9]\d*|0)?(?:\.\d+)?$
Problem is that it rejects 1.
which is a valid number (you can verify from the immediate window in VS). Could be other edge cases I did not test. Please advise.
P.S. I included ASP.NET and C# tags because this is for a web application written in C#, in which this regular expression is passed to a 3rd party component, which then works on the client (i.e. JS), so I cannot easily put custom code there (i.e. decimal.TryParse
or smth like that).
Upvotes: 2
Views: 1036
Reputation: 785008
You can use this regex based on a negative lookahead to avoid matching single dot:
^(?!\D+$)\+?\d*?(?:\.\d*)?$
(?!\D+$)
is negative lookahead to assert failure when input is non digit characters?:\.\d*)?
allows for matching 123.
type of number.Upvotes: 3