Validating a decimal value against a regular expression

rgn2121
rgn2121 used Ask the Experts™
on
I am tryin to use a regular expression to validate that my decimal has no more than 4 places after the decimal.

I tried the code below, but even when I use a number like 2.23456 it still comes back as success=true...what am I doing wrong?

            Dim qtyMatch As Match = Regex.Match(QuantityValue.ToString, "\d+\.?\d?\d?\d?\d?")
            If qtyMatch.Success = False Then
                'Error
            End If
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The way your regex is written, it will match any string that contains at least one digit.  Why?  Every expression is optional (followed by a question mark) except the first (\d), which is followed by a plus (meaning it is satisfied by a single instance).

You also have no anchors (^ or $), so you are not requiring that your entire value matches your value.  This means that it will match if it matches anywhere in the string (e.g., abc1xyz will match).

A better regex is:
"^\d+(?:\.\d{0,4})?$"
Or (if negative values are allowed):
"^-?\d+(?:\.\d{0,4})?$"

The above regexes require the entire string to be a string of digits, followed by an optional decimal point and up to four digits.  The second regex allows an optional negative sign at the beginning as well.
As an explanation:
^ - Start of the string
-? - Optional dash (negative)
\d+ - One or more digits
(?: - Start of non-capturing pattern group
\. - Period / decimal
\d{0,4} - Zero to four digits
)? - End of non-capturing group (which is optional because of the question mark)
$ - End of the string

If any part of the string does not match the above, it will be rejected as a non-match.

Author

Commented:
Great ...Thanks!  The code I posted was in a regularExpression Validator.  Those must wrap the regex so that it knows to check the full string.
kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
The code I posted was in a regularExpression Validator.  Those must wrap the regex so that it knows to check the full string.
Yes:  When dealing with a RegularExpressionValidator the ^ and $ are implied. It doesn't hurt to add them; it doesn't hurt to leave them out.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial