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 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C