2

i am trying to valdiate the date field "YYYYMMDD" using PHP regex. I tried something like this

/([0-9]{4})([0-9]{2})([0-9]{2})/

but in this one, it's going to accept any two digits like 01-99 for MM or DD, but i am looking to have something for 01-12 for MM and 01-31 for DD. Any advise on doing this?

thanks

3
  • 2
    Probably need to add some PHP code for validation also Commented Apr 26, 2011 at 19:19
  • 2
    Regexes are NOT the way to valid dates, except in the grossest way (e.g. "it's all digits"). '2011-02-29' would get accepted, even though that's not valid date as 2011 isn't a leapyear. Commented Apr 26, 2011 at 19:28
  • @all, i agree with the reasons, will write a php fucntion. thanks. Commented Apr 26, 2011 at 19:41

5 Answers 5

4

This should do the job:

function dateValidate($date) {
    $t = strtotime($date);
    return date('Ymd', $t) == $date;
}

edit: Worth noting that this won't be as fast as a regexp but in terms of noticeable performance will work fine.

Sign up to request clarification or add additional context in comments.

Comments

3

Instead of regular expressions you can also split the string and use checkdate to see if the date is valid.

3 Comments

how would i split 20091010 into 3 parts? i don't have any delimiter, should i go with counting the digits and split it?
If you're sure you have YYYYMMDD you can use substr().
thanks, i did this way and it worked. thanks all. how would i put my sample code here? is it [code] tabg?
1

Regex doesn't seem very practical for date validation. Why not split it into pieces, then use checkdate()?

Comments

0

For the month, you could use:

(0[1-9]|1[012])

For days:

(0[1-9]| [12][0-9]|3[01])

Some good examples here.

2 Comments

What about months shorter than 31 days/leap years etc.? IMHO full validation would be too cumbersome to do with regexp only.
True, shorter versions wont work... given format was YYYYMMDD.
0

DO NOT USE checkdate as checkdate('1\'', '1', '2000') validates TRUE.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.