DD在PHP中验证日期

DD在PHP中验证日期

本文介绍了正则表达式使用格式为YYYY-MM-DD在PHP中验证日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个日期正则表达式验证器。我遇到的问题是,我正在使用一个输入字段,其中包含date类型,它的作用就像Chrome中的魅力;它在Chrome中打开一个日历,但在其余的它什么都不做,所以我决定去手动输入其余日期。

I am trying to make a date regex validator. The issue I'm having is that I'm using an input field with "date" type, which works like a charm in Chrome; it opens a calendar-like in Chrome, but in the rest it does nothing, so I decided to go for a manual input of the date for the rest.

这是我的错误消息(我正在寻找YYYY-MM-DD格式):

This is my error throwing message (I'm looking for YYYY-MM-DD format):

$date_regex ='#^(19|20)\d\d[\- /.](0[1-9]|1[012])[\- /.](0[1-9]|[12][0-9]|3[01])$#';
$hiredate = $_POST['hiredate'];
if (!preg_match($date_regex, $hiredate)){
    $errors[] = 'Your hire date entry does not match the YYYY-MM-DD required format.';
}

我知道这里有很多例子,但是我尝试了20已经和我无法解决。也许我错过了一些东西。

I know there are a lot of examples about this, but I tried like 20 already and I couldn't solve it. Maybe I'm missing something.

这是输入字段,如果有些相关:

Here's the input field, if somewhat relevant:

<input type="date" name="hiredate" />


推荐答案

你的正则表达式没有工作,因为你有>未转义 / 分隔符。

Your regex didn't work because you had unescaped / delimiter.

正则表达式将以 YYYY-MM-DD 如下:

^(19|20)\d\d[\-\/.](0[1-9]|1[012])[\-\/.](0[1-9]|[12][0-9]|3[01])$

它将验证年份以 19开始 20 ,该月份不超过 12 而不等于 0 而且该日期不大于 31 并且不等于 0

It will validate that the year starts with 19 or 20, that the month is not greater than 12 and doesn't equal 0 and that the day is not greater than 31 and doesn't equal 0.

使用您的初始示例,您可以这样测试:

Using your initial example, you could test it like this:

$date_regex = '/^(19|20)\d\d[\-\/.](0[1-9]|1[012])[\-\/.](0[1-9]|[12][0-9]|3[01])$/';
$hiredate = '2013-14-04';

if (!preg_match($date_regex, $hiredate)) {
    echo '<br>Your hire date entry does not match the YYYY-MM-DD required format.<br>';
} else {
    echo '<br>Your date is set correctly<br>';
}

这篇关于正则表达式使用格式为YYYY-MM-DD在PHP中验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:36