简体   繁体   English

日期正则表达式未返回真

[英]Date Regular Expression Not Returning True

For some reason this is always returning false... when entering "2014 12 12" into the form. 由于某种原因,当在表单中输入“ 2014 12 12”时,它总是返回false...。 It is this format to enter into a database. 进入数据库就是这种格式。

$date = trim($_POST['date']);

in my library.php i have : 在我的library.php中,我有:

function validateDate($date) {
    if(preg_match('/^[0-9]{2,4}[\-[[:space:]]]{1}[0-9]{1,2}[\-[[:space:]]]{1}[0-9]{1,2}$/',$date)){
        return true;
    }
    else{
        return false;       
    }
}

and in my php i have : 在我的PHP中,我有:

if (validateDate($date)){
    $dateCSS = 'style="border-color: #98faad;"';
}
else {
    $dateCSS = 'style="border-color: red;"';
    $flag = false;
}

试试这个正则表达式:

^[0-9]{2,4}[\-[:space:]]{1}[0-9]{1,2}[\-[:space:]]{1}[0-9]{1,2}$

A more reliable way to validate a date is to use the datetime extension . 验证日期的一种更可靠的方法是使用datetime扩展名

function validateDate($date, $format = 'Y d m') {
    return \DateTime::createFromFormat($format, $date) !== false;
}

This way you do not have to resort to using regular expressions, and you will be able to actually validate dates correctly (for example, something like 2014 12 51 will not validate). 这样,您就不必求助于使用正则表达式,并且您将能够正确地验证日期(例如,类似2014 12 51将无法验证)。

if ( ! validateDate('2014 12 51')) {
    echo 'Not valid!';
}

It will also allow you to validate more complicated dates, if you will be required to do that some day: 如果有一天需要这样做,它还允许您验证更复杂的日期:

if (validateDate('16th September 2014', 'dS F Y')) {
    echo 'Valid!';
}

For the $format argument you must use the formatting options that DateTime::createFromFormat() accepts. 对于$format参数,您必须使用DateTime::createFromFormat()接受的格式设置选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM