views:

2012

answers:

6

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?

Thanks, ~ck in San Diego

+4  A: 

This has been addressed in this post. See if it helps.

JYelton
+17  A: 

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.

Donut
Agreed, let the framework pull the weight on this one.
Matthew Vines
And DateTime.TryParseExact() may be more appropriate depending on your exact needs.
Matthew Vines
+9  A: 

You can use DateTime.TryParseExact:

DateTime dt;

bool isValid = DateTime.TryParseExact(
    "08/30/2009",
    "MM/dd/yyyy",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out dt);
dtb
A: 

This isn't really an answer, but couldn't you use DateTime.Parse or DateTime.TryParse to check that the date is correct?

Either that or use a DateTime control to make sure it's impossible to enter data that isn't a DateTime. There's lots of Javascript out there on this subject.

Oplopanax
+2  A: 

Kettenbach had a problem. His co-worker suggested using regexs. Kettenbach then had two problems.

as others have said, use DateTime.TryParse or DateTime.TryParseExact on a custom validator and save yourself the nightmare that is regex :)

Sk93
Regexes aren't inherently evil. They need to be used judiciously, though. They work great for a certain class of text parsing problems.
TrueWill
oh I never said they were evil, per say... But they are on a level with cats.
Sk93
Please attribute the above statement to Jamie Zawinski.
Jason
A: 

Last answer is actuallu correct way to do. Use DateTime.TryParse

Example: DateTime dt; if(DateTime.Tryparse(Textbox1.Text,Out dt) { Label1.Text = "Invalid date"; }

wwd
I was writing actual code for it.
wwd