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
Here are the details: The regex will match a string only if it contains at least one valid date, like: [dd-mm] Assuming the year in question is not a leap year. The number of days each month should have are: January 31 days February 28 days So on All text outside a valid date can be ignored, including other invalid dates.
A regular expression for dates (YYYY-MM-DD) should check for 4 digits at the front of the expression, followed by a hyphen, then a two-digit month between 01 and 12, followed by another hyphen, and finally a two-digit day between 01 and 31. Here’s the regex code that does all this: /^d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
The month is matched by 0[1-9]|1[012], again enclosed by parentheses to keep the two options together. By using character classes, the first option matches a number between 01 and 09, and the second matches 10, 11 or 12. The last part of the regex consists of three options.
Regular Expression for YYYY-MM-DD Dates A date should start with a 4 digit year from 0000-9999. We can specify this using the following: /d {4}/
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With