Andrey
Andrey

Reputation: 1769

Regex to validate numbers and forward slashes for date

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

Upvotes: 1

Views: 2784

Answers (2)

Qtax
Qtax

Reputation: 33928

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$

Upvotes: 2

Dai
Dai

Reputation: 155726

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.

Upvotes: 7

Related Questions