简体   繁体   中英

How to create a datetime validator in a Zend Framework form?

By default a Zend Framework date validator uses the date format yyyy-MM-dd :

$dateValidator = new Zend_Validate_Date();

But I want to add hour and minute validation. In other words, I want to require the user to enter the hour and minute. But the following does not work:

$dateValidator = new Zend_Validate_Date('yyyy-MM-dd hh:ii');

If I enter 2010-02-01 , I get an error saying that the date doesn't fit the format. If I enter 2010-02-01 3 , it doesn't complain. What's it's doing is assuming that the user means 2010-02-01 03:00 rather than enforcing that the user enters the date in the given format.

How can I enforce that the date must be entered in the given format?

Please see: http://framework.zend.com/issues/browse/ZF-6369

Basically what it comes down to is that the code underlying the format validation doesn't work correctly. Rather than using strict validation, it will try to coerce the provided date into something that will validate and so you get hanky results.

It does look like the bug has been marked as 'Major' so hopefully we'll see a fix soon.

To add to Noah's answer, Zend_Validate_Date is really quite awful and inflexible; that is if you want to have a more forgiving policy for date entry.

Now, if ZF shipped with a Zend_Filter_Date that would normalize the various trivial (albeit very parseable) formats date selectors / user input supplies, that might be a different story as you could filter the date to a normalized format, then validate it that it is in that format. But it doesn't.

No matter though, there are plenty of sane solutions to this problem. Probably the easiest of which is this:

$validator = new \Zend_Validate_Callback(function($value) {
    return (bool)strtotime($value);
});

Personally, I don't care whether a date / datetime comes in as yyyy/MM/dd, Sept 23, 2012, or as "-2 weeks" -- all I really care about is whether or not strtotime is smart enough to parse it.

+1 to Stephen's answer. I went for a similar solution, since I already knew the format I had to validate:

$validator = new \Zend_Validate_Callback(function($value) {

    return (bool) date_create_from_format('Y-m-d H:i', $value);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM