doushao8421 2013-11-17 06:12
浏览 429
已采纳

正则表达式生日验证

I have a regex which validate birthday:

if(!preg_match('/^(0?[1-9]|1[012])[- .\/](0?[1-9]|[12][0-9]|3[01])[- .\/](19|20)?[0-9]{2}$/', $_POST['bday'])
{
    echo 'enter your birthdate in a valid format. mm/dd/yyy';
}

which is:

correct month

leap year date is not accurate

february accepts day 30 & 31

and the year 20 accepts greater than 2013

I only done correct with months how can I do more accurate birthday validation? or there is any alternate way to validate birthday?

my desired output is:

validate leap year date on month of february

year must not greater than 2010

OUTPUT:

02/14/2010

I'm just quite new on regex kindly help?

  • 写回答

1条回答 默认 最新

  • dongshi1215 2013-11-17 06:19
    关注

    A regex isn't well-suited for parsing dates. PHP already has built-in functions and classes to do this and you should use that instead. Here's how this can be done using PHP's DateTime class (function by Glavić, from php.net):

    function validateDate($date, $format = 'm/d/Y')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date && $d->format('Y') <= 2010;
    }
    

    For example:

    var_dump(validateDate('02/14/2010')); // bool(true)
    var_dump(validateDate('02/14/2011')); // bool(false)
    

    Demo!

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序