tags:

views:

389

answers:

5

I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET

+2  A: 

I don't think this is a task very well-suited for a regexp.

I'd try and use the library functions (DateTime.Parse for .NET) to parse the date and then check the day component of it. Everything else is duplicating half the library function anyways.

pilif
+1  A: 

Why not just covert it to a date data type and check the day? Using a regular expression, while it could be done, just makes it overly complicated.

Kibbee
+17  A: 

Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:

DateTime parsedDate;

if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
{
 // logic goes here.
}

Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.

Simon Johnson
+1  A: 
  ([1-9]|1\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits
(0?[1-9]|1\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09

(where \d matches any digit, use [0-9] if your regex engine doesn't support it.)

See also the question What is the regex pattern for datetime (2008-09-01 12:35:45 ) ?

Sam Hasler
A: 

I would use one of the DateTime.TryParse techniques in conjunction with a CustomValidator

John Sheehan