views:

1007

answers:

4

Hello!

We are using a RegEx Validator to validate an input from a textbox.

The current RegEx expression checks if the current number is between the range of 1 - 999.

We just inherited this code and we need to change the range from 999 to just 365. In short, we need to write a regex to check if the input is between 1 - 365.

Of course, we can just use a RangeValidator or a custom validator. But we don't want to do that because we don't want to introduce a "significant" change.

Thanks!

EDIT:

We should also catch this following patterns: 001 for 1 019 for 19

+10  A: 

Using regular expressions is certainly not the best way to validate integer ranges, but here you go:

 ^([1-9][0-9]?|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$

[1-9][0-9]?     matches    1 -  99
[12][0-9][0-9]  matches  100 - 299
3[0-5][0-9]     matches  300 - 359
36[0-5]         matches  360 - 365

EDIT: With leading zeros (also matches strings like 00000000321):

 ^0*([1-9][0-9]?|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$
Ferdinand Beyer
Does this cover single digit numbers?
Oli
Sure. [1-9][0-9]? covers 1-99.
Ferdinand Beyer
This is failing for 100 upwards. :(
Ian
Please show some concrete strings that are failing.
Lasse V. Karlsen
100205300123
Ian
@lan: I forgot to use parantheses. Please try again using the updated pattern – it should work now!
Ferdinand Beyer
@Ferdinand -- Great! Its working perfectly. :)
Ian
What about 001?
Hao Wooi Lim
@Hao: It even matches 317!
Ferdinand Beyer
+3  A: 

Mind the gap, ehm leap year. :-)

Matej
+1 ... Well, 1-365 could be *anything*, really. Why do you think it is for validating days in a year? ;-)
Tomalak
365 seems to be a rather random number is it is not the number of days in a "normal" year...
Mike Cooper
+2  A: 

you really don't want to use regex for that, you should just use /^\d{1,3}$/ and validate the number as being 1..365

as for just regex:

SNIP

ferdinands is fine :)

Luke Schafer
This is more sensible approach.
chappar
+1  A: 

Little addition to Ferdinand's regexp for catching leading zeros:

^([0]{0,2}[1-9]|[0]?[1-9][0-9]|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$

[0]{0,2}[1-9]  - catches 001, 01, 1...
[0]?[1-9][0-9] - catches 010, 10...

Notice, it does not catch 0234 or 0019

Savash
That is not really a problem because the textbox only allows for 3 characters. :)
Ian
But anyway, good catch. I'll be adding your fix. :)
Ian