1

I need a RegEx to check if an item order count is either 0 or between 2500 and 999999. Is this even possible to do?

Example: You can either order 0 (no items) or you have to make an order of 2500 or more items.

Update: This need to be a RegEx because it will be used in a validation attribute in MVC.

[RegularExpression(@"SomeRegExpression", ErrorMessage = "Min order error")]
Stian
  • 1,261
  • 2
  • 19
  • 38
  • 1
    your question is not clear... Can you make an example ? – aleroot May 22 '12 at 08:03
  • 6
    C# has operators for comparing numbers which are much easier to use than a regex :) – Stilgar May 22 '12 at 08:03
  • Yes, but this is used in a validation attribute in MVC model like this: [RegularExpression(@"SomeRegExpression", ErrorMessage = "Min order error")] – Stian May 22 '12 at 08:05
  • 1
    Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. – David Brabant May 22 '12 at 08:05
  • I would of course like to use [Range(2500, int.MaxValue, ErrorMessage = "You need to order minimum {1} of Item1")] - but this will not allow zero. – Stian May 22 '12 at 08:06

2 Answers2

3

If it has to be a regex:

^(?:0|\d{5,6}|2[5-9]\d\d|[3-9]\d\d\d)$

Explanation:

^                # Start of string
(?:              # Either match...
 0               # 0
|                # or
 \d{5,6}         # a five- or six-digit number
|                # or
 2[5-9]\d\d      # 2500-2999
|                # or
 [3-9]\d\d\d     # 3000-9999
)                # End of alternation
$                # End of string
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Wow - that is a just great! Thanks for the explanation :) Is there a way to say that it must be above 2500 with no max value? (I can control this myself in the text input). – Stian May 22 '12 at 08:15
  • 1
    @Stian: Replace `\d{5,6}` by `\d{5,}`. This replaces "five- or six-digit number" with "at least five digit number". – Heinzi May 22 '12 at 08:24
3

You could also write your own custom validation attibute.

See How to create custom validation attribute for MVC and/or http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC-3 for examples.

For example;

public class CustomValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        int number = value as int;
        return (number == 0 || (number >= 2500 && number <= 999999));
    }
}
Community
  • 1
  • 1
Stefan
  • 5,644
  • 4
  • 24
  • 31