tags:

views:

73

answers:

3

I have a regex used to validate dates:

^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

Works really well, but I am using it all over the place with asp.net regex validators and I want to minimize it so I can reduce page size. It works with dd/mm/yyyy format and handles leap years. I'm looking for a more concise regex statement.

+6  A: 

How about this one:

^(\d{1,2})\/(\d{1,2})\/(\d{4})$

Then, once you've got the digits out, use program logic to validate whether the date makes sense. It's insane to try to do that inside your regular expression, as you've noticed.

Greg Hewgill
Upvoted three times.
BipedalShark
Avoiding using only the regex hammer for an non-nail shaped problem :)
VonC
+2  A: 

You could just make a class DateValidator that has a Validate method and uses this regex, and everyone else can reference that class/method.

If you can't create a new class to contain this validation, could you at least hide it behind a global string constant?

That way, if you ever change your regex, you only change it in 1 place instead of 1000 places.

FrustratedWithFormsDesigner
I've implemented it in asp.net using a regex validator and a skin, so I only define it in once place, but when the html renders, it renders the regex once for each validator. ugg
Jeremy
+1  A: 

Dude, there's a difference between parsing and validating. I'd separate the two. A regex is fine for parsing a date into a date object. Use something else to determine if it refers to an existent point in time, ie is it valid.

sblundy