-1

I'm trying to validate the date and month in below format:

MM/dd

And now, I'm using this regex to validate:

(0[1-9]|1[0-2])\/(3[0-1]|2[0-9]|1[0-9]|0[1-9])

And the regex successfully validate these formats:

    //Below are valid dates    
    09/05
    01/01
    12/30
    10/30
    //Below are invalid dates
    11/31
    09/31

How to modify the regex so that it also checks the days in month?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
User2012384
  • 4,769
  • 16
  • 70
  • 106

1 Answers1

4

I don't think regex is the right way to do this. Use DateTime parsing instead with MM/yy format and a culture that have / as a DateSeparator.

string s = "12/31";
DateTime dt;
if(DateTime.TryParseExact(s, "MM/dd", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // Valid
}

By the way, September and November have 30 days, not 31. That's why 09/31 and 11/31 are invalid.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364