Hi does any one know a reg ex for a uk date format e.g. dd/mm/yyyy.
The dd or mm can be 1 character e.g. 1/1/2010 but the year must always be 4 characters.
Thanks in advance
^\d{1,2}/\d{1,2}/\d{4}$
will match 1/1/2000, 07/05/1999, but also 99/77/8765.
So if you want to do some rudimentary plausibility checking, you need
^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}$
This will still match 31/02/9999, so if you want to catch those, it's getting hairier:
^(?:(?:[12][0-9]|0?[1-9])/0?2|(?:30|[12][0-9]|0?[1-9])/(?:0?[469]|11)|(?:3[01]|[12][0-9]|0?[1-9])/(?:0?[13578]|1[02]))/\d{4}$
But this still won't catch leap years. So, modifying a beast of a regex from regexlib.com:
^(?:(?:(?:(?:31\/(?:0?[13578]|1[02]))|(?:(?:29|30)\/(?:0?[13-9]|1[0-2])))\/(?:1[6-9]|[2-9]\d)\d{2})|(?:29\/0?2\/(?:(?:(1[6-9]|[2-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:0?[1-9]|1\d|2[0-8])\/(?:(?:0?[1-9])|(?:1[0-2]))\/(?:(?:1[6-9]|[2-9]\d)\d{2}))$
will match
1/1/2001
31/5/2010
29/02/2000
29/2/2400
23/5/1671
01/1/9000
and fail
31/2/2000
31/6/1800
12/12/90
29/2/2100
33/3/3333
All in all, regular expressions may be able to match dates; validating them is not their forte, but if they are all you can use, it's certainly possible. But looks horrifying :)
Regex is not the right tool for this job.
It is very difficult (but possible) to come up with the regex to match a valid date. Things like ensuring Feb has 29
days on leap year and stuff is not easily doable in regex.
Instead check if your language library provides any function for validating dates.
PHP has one such function called checkdate :
bool checkdate ( int $month , int $day , int $year)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With