0

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.

2
  • What if I like my dates to be His? Those separators like colon and slash are for pussies, I like 'em dates solid. I also like the date say "I've got balls of steel at His." But you would consider this wrong format. Kidding aside, I think if this is for advanced users, let them do the formatting as they like. Commented Jan 28, 2012 at 7:41
  • Yes, you are right. Thanks. Actually I can keep my solution and if it displays the string itself, he will change the format. It is for advanced user only Commented Jan 28, 2012 at 7:44

1 Answer 1

3

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.

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

1 Comment

Feel free to upvote it and mark it as accepted if no one posts a better answer after a while :p. (Woo pandering! :) )

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.