duanji8887 2012-09-25 11:46
浏览 19
已采纳

使用Zend_Filter_Input验证日期

I'm using ZF 1.11 and want to validate a non-Zend_Form with Zend_Filter_Input. I've successfully set up my basic validation, but I'm trying to pre-validate the credit card expiration date before sending it to the processor, to be greater than today's month/year.

Is this possible? I haven't seen any specific date validation on their docs, other than validating both month/year fields as numbers in a certain range.

Edit: I want to do this without creating a new validation class (or extending/implementing an existing one), as I've seen on other questions on SO.

  • 写回答

1条回答 默认 最新

  • douyan8266 2012-09-25 20:41
    关注

    In general I recommend to write a custom validator as this is in my opinion the cleanest way to handle such cases in ZF.

    To my knowledge the Date validator only checks for the formal validity of a date but cannot compare two dates. However, with the restriction in mind to use only built in Zend Framework validators I came up with a somewhat hacky solution using the GreaterThan validator:

    <?php
    $year = 2012;
    $month = 1;
    $inputDatePast = intval(sprintf('%4d%02d', $year, $month)); //201201
    
    $year = 2016;  // if you read this after september 2016: add a few more years here ;)
    $month = 9;
    $inputDateFuture = intval(sprintf('%4d%02d', $year, $month)); //201609
    
    $prevMonth = intval(date('Ym', mktime(12, 0, 0, date('n')-1, 1, date('Y'))));
    
    $validator = new Zend_Validate_GreaterThan($prevMonth);
    $validator->isValid($inputDatePast); // false
    $validator->isValid($inputDateFuture); // true
    ?>
    

    So the idea is to create an integer out of the previous month's year and month and compare if a given year and month is greater than this value. This integer is created by four digits for the year and two digits (the leading zero is important) for the month.

    As an example September 2012 is 201209. If a user inputs October 2011 this would be 201109 which is smaller than 201209 and consequently evaluates to false. On the other hand, if a user enters January 2014 this would be 201401 which is greater than the previous date.

    Please note that this is only an untested sketch and probably needs some more consideration and validation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀