How to create a date and time validator in a Zend Framework form?

By default, the Zend Framework Date Checker uses the yyyy-MM-dd date format:

 $dateValidator = new Zend_Validate_Date(); 

But I want to add an hour and minute check. In other words, I want the user to enter an hour and a 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 a message that the date does not match the format. If I introduce 2010-02-01 3 , he will not complain. He makes the assumption that the user means 2010-02-01 03:00 instead of forcing the user to enter a date in this format.

How can I guarantee that the date should be entered in this format?

+3
source share
3 answers

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

Basically, what happens is that the code underlying the format check does not work correctly. Instead of using strict validation, it will try to force the provided date to something that will be verified, and therefore you will get hanky results.

It seems that the error is marked as "Major", so I hope to see the fix soon.

+4
source

To add to Noah's answers, Zend_Validate_Date really awful and inflexible; that is, if you want to have a more forgiving policy for entering dates.

Now, if ZF was sent with Zend_Filter_Date , which normalizes various trivial (albeit very syntactic) date picker / user input formats, this could be a different story, since you can filter the date in a normalized format, then confirm that it is in this format . But this is not so.

Despite this, there are many reasonable solutions to this problem. Probably the easiest one:

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

Personally, it doesn’t matter to me whether the date / date is included in yyyy / MM / dd, September 23, 2012 or as β€œ-2 weeks” - all I really care about is the ability to strtotime enough to parse it.

+4
source

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

 $validator = new \Zend_Validate_Callback(function($value) { return (bool) date_create_from_format('Ymd H:i', $value); }); 
+1
source

Source: https://habr.com/ru/post/1482901/


All Articles