I would like to create a function which validates a date string.
My module displays a date, and in the backend there are some example formats the user can use to display the date on the frontend, and also an advanced date format input where he can specify a date format string like ‘H:i:s’ or whatever he wants.
If no advanced format option is specified, it uses the default format.
To check the validity of the enterred format in the input, I thought I can do :
$now = new Datetime(‘now’);
if (!$now->format($format)) …. false format
But the format method doesn’t return false if $format = x or efkjfkefefje, it just returns the string itself.
I would like it to return false if there is a caracter that differs from the specified caracters here : http://www.php.net/manual/en/function.date.php
But there are so many cases. For example ‘H:i:s’ would be valid but ‘His’ Won’t be.
I don’t want it to parse the ‘:’ or ‘/’, I mean we can consider that ‘H/i/s’ is valid, because it’s an input for advanced users only.
I would like it to return false if a caracter differs from the list here http://www.php.net/manual/en/function.date.php or if there is no space between caracters : ‘His’ is not valid whereas the 3 caracters alone are.
I’m not very familiar with regex.
To validate a date format string, you should be able to use DateTime::createFromFormat.
http://www.php.net/manual/en/datetime.createfromformat.php
It returns either a DateTime object if it’s created successfully, or false if the date string provided does not match the format.