tags:

views:

86

answers:

3

I have to validate using regex decimal number between 00.00 to 35.35 with following simple assumptions(I am using C#).

1) leading zeros are not required(optional). 2) 2 decimals are always required.

In other words, it should be a decimal number within a range with 2 decimal points.

Examples of valid numbers are: 0.00, 00.00, .67, 2.89 and should fail on those numbers: 8.9999(4 decimals), 65.00(out of range)

I had no difficulty to validate 2 decimal points but don't know how to do the range? Is this something that even can be done using regex?

A: 

Try this regular expression:

^(0?\d|[12]\d|3[0-4])?\.\d\d$|^35\.([02]\d|3[05])$
Gumbo
The upper limit is 35.35, so `35.56` should not pass.
KennyTM
Validating against 35.35 (or any numeric values) should not be done as a part of the regex. It's possible but makes things very sticky and messy.
FrustratedWithFormsDesigner
@Frustrated Yes, I would agree with that, just by looking at RegEx above.
Victor
This one works, thank you
Victor
+4  A: 

Seriously. Use RegEx to check that the input matches ^\d{1,2}\.\d{2}$, then convert it into a number and check 0 <= x && x <= 35.35. RegEx is not designed to be a calculator.


If you insist:

^(?:(?:[012]?\d|3[0-4])\.\d{2}|35\.(?:[012]\d|3[0-5]))$
KennyTM
+1 Some people insist on using RegEx to solve everything. Like using a hammer to paint a picture..Possible, not recommended
Cody C
@Cody C: Painting a picture with a hammer could get you praise from some of the more 'creative' contemporary artists out there. Especially if you make a performance out of it.
FrustratedWithFormsDesigner
+2  A: 

I would use Decimal.TryParse. E.g.:

    private const decimal min = 0.0M;
    private const decimal max = 35.35M;
    static bool inRange(string s)
    {
        Decimal d = new Decimal();
        if (Decimal.TryParse(s, out d))
        {
            return d > min && d < max;
        }
        else
            return false;
    }
fatcat1111
Thanks for reply. Yes, that's what I am wondering - is it better to use RegExValidator or just a CustomValidator with method like this.
Victor
@VictorS: I would think this is much better than using a regex, but maybe you are in a situation that REQUIRES a regular expression.
FrustratedWithFormsDesigner
@VictorS: The other nice thing about this approach is that you can put this functionality into a `DecimalRangeValidator` class and then reuse it for other ranges (if you have them) by parameterizing the max, min, and test value, rather than having to write a new expression for every range you want to test.
FrustratedWithFormsDesigner