This question already has an answer here:
- Validate date format in php 7 answers
function validateDate( $date )
{
echo $date;
//2012-08-24 20:30:00
if(preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([1-2]{1})([0-9]{1}):([0-5]{1})([0-9]{1}):([0-5]{1})([0-9]{1})$/', $date) >= 1)
{
return true;
}
else
{
return false;
}
}
This always returns false. I used an only tool to build the regular expression and it was working fine there. Trouble started when I added the "/" to the regex. Somehow PHP seems to require these but I dont know why and I dont know why it breaks my regex.
It should return TRUE for sth. like "2012-08-24 20:30:00" and FALSE for "asdf2012-08-24 20:30:00asdf" or anything thats not acording to my regex
Thanks in advance!
-----------------------EDIT Thanks for all your answers!
As some users pointed out my function returns true for the sample date "2012-08-24 20:30:00". However it does that only if i manually set $date='2012-08-24 20:30:00'. If i call the function elsewhere in my code with the exact same string it returns false. Does anyone know why?
-----------------------EDIT2
Yea sorry for wasting your time, it was in fact some whitespace that was added to the string. using trim() on my date before calling my function gives the correct result now.
thanks everyone!
Returns
true
for me. Try this regex instead:It is easier to validate format in RegEx, followed by validating content with targeted functions, than to try and do everything in RegEx.
This should work better, and be more simply written:
However it will return true with
9999-99-99 29:59:59
as others mentioned...From PHP manual, you can easily find more elegant and reliable solutions, for example (inspired from this comment):
What you are asking about are the delimiters. Read this article in PHP.net's manual: RegExp - Delimiters
And:
Why use regex? Use DateTime class.
You can use this function for all kind of date/time validations. Examples: