Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UK Date Regular Expression [duplicate]

Tags:

regex

I'm trying to create a regular expression that validates UK date format. I have the following:

(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d

This works great for validating: 09/12/2011. But if the date is: 9/12/2011 it will not validate correctly. Is there a regular expression that allows me to use a single number and two numbers for the day section? For example "09" and "9".

like image 924
Funky Avatar asked Dec 17 '22 17:12

Funky


1 Answers

Just make the leading 0 optional:

(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)\d\d

You will need an additional validation step, though - this regex of course won't check for invalid dates like 31-02-2000 etc. While it's possible to do this in regex, it's not recommended because it's much easier to do this programmatically, and that regex is going to be monstrous. Here is a date validating regex (that uses the mmddyyyy format, though) to show what I mean.

like image 173
Tim Pietzcker Avatar answered Jan 04 '23 23:01

Tim Pietzcker