开发者

smaller date regex

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})开发者_StackOverflow)|((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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜