1

Hi I am trying to wright Regular Expression for date mm/dd/yyyy C#. I have this

^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$

But it doesn't work
enter image description here

How to do so it will works with 3/1/2013 and with 03/01/2013

Community
  • 1
  • 1
Andrey
  • 1,629
  • 13
  • 37
  • 65

2 Answers2

7

Don't use regular expressions, use DateTime.TryParse or DateTime.TryParseExact.

Also be aware of the current culture and the user's expectations. Americans use "MM/dd/yyyy" but the rest of the world (generally) uses "dd/MM/yyyy", both are indistinguishable for large ranges of dates.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • app will used only in US and I am using Ajax datatime picker – Andrey Mar 22 '13 at 01:44
  • Just in case you're using JSON input using MS serialized dates and failing to tryparse the values, try: http://stackoverflow.com/questions/1263732/how-to-pass-a-json-date-value-via-asp-net-mvc-using-json-net – bob-the-destroyer Mar 22 '13 at 01:58
2

I agree that you should use DateTime methods for this. But if you want to make the leading zeros optional you can add a ? after them, like so:

^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$
Qtax
  • 33,241
  • 9
  • 83
  • 121