Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regular Expression to validate a date?

I am trying to validate a date entered into a text box. There is an input mask on the textbox which forces input of xx/xx/xxxx. I am trying to use a regular expression validator to enforce that a correct date is entered. I am not skilled in RegEx bascially at all. My co-worker found this one on the internet but I can't really tell what it's doing.

Does this look right? Seems overly complicated...

(^((((0[1-9])|([1-2][0-9])|(3[0-1]))|([1-9]))\x2F(((0[1-9])|(1[0-2]))|([1-9]))\x2F(([0-9]{2})|(((19)|([2]([0]{1})))([0-9]{2}))))$)

Does anyone know of a less complex expression that essentially does what I need?

like image 298
Hcabnettek Avatar asked Aug 31 '09 20:08

Hcabnettek


2 Answers

Why not use one of the methods available in the System.DateTime namespace? You could use DateTime.TryParse() (edit: DateTime.TryParseExact() is probably the right suggestion) to accomplish the validation.

like image 126
Donut Avatar answered Sep 22 '22 06:09

Donut


You can use DateTime.TryParseExact:

DateTime dt;

bool isValid = DateTime.TryParseExact(
    "08/30/2009",
    "MM/dd/yyyy",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out dt);
like image 32
dtb Avatar answered Sep 22 '22 06:09

dtb