preg_match:检查生日格式(年/月/日)

lau*_*kok 10 php regex preg-match

如何使用检查生日输入的表达式匹配像dd/mm/yyyy这样的格式?以下是我到目前为止所发布的内容,但如果我把它放到99/99/9999那也需要这个!

if (!preg_match("/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/", $cnt_birthday))
  {
   $error = true;
   echo '<error elementid="cnt_birthday" message="BIRTHDAY - Only this birthday format - dd/mm/yyyy - is accepted."/>';
  }
Run Code Online (Sandbox Code Playgroud)

如何确保dd仅为01到31,mm为01到12?但我相信如何限制yyyy ...我认为理论9999应该是可以接受的......如果你有更好的主意,请告诉我!

谢谢,刘

Tim*_*ain 25

我建议使用checkdate()代替:

if (preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $cnt_birthday, $matches)) {
    if (!checkdate($matches[2], $matches[1], $matches[3])) {
        $error = true;
        echo '<error elementid="cnt_birthday" message="BIRTHDAY - Please enter a valid date in the format - dd/mm/yyyy"/>';
    }
} else {
    $error = true;
    echo '<error elementid="cnt_birthday" message="BIRTHDAY - Only this birthday format - dd/mm/yyyy - is accepted."/>';
}
Run Code Online (Sandbox Code Playgroud)

因此regexp验证格式,checkdate验证实际日期.


cod*_*ict 24

基于蒂姆checkdate解决方案:

使用explodeas 可以轻松完成日,月和年的提取:

list($dd,$mm,$yyyy) = explode('/',$cnt_birthday);
if (!checkdate($mm,$dd,$yyyy)) {
        $error = true;
}
Run Code Online (Sandbox Code Playgroud)