开发者

i want create date validation but not know why return is false?

开发者 https://www.devze.com 2023-03-21 16:21 出处:网络
i want create date validation but not know why return is false? $data_go = \'2011/04/28\'; $ddmmyyy=\'(0[1-9]|[12][0-9]|3[01])[- \\/.](0[1-9]|1[012])[- \\/.](19|20)[0-9]{2}\';

i want create date validation but not know why return is false?

$data_go = '2011/04/28';
$ddmmyyy='(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)[0-9]{2}';
            if(preg_match("/$dd开发者_Go百科mmyyy$/", $data_go)) {
               return TRUE;
            }else {
              return FALSE;
            }


Because your date is yyyy/mm/dd, while your Regex is dd/mm/yyyy.


i'm not much familiar with regex (shame on me) but you can always use the checkdate() method to validate a date server side.

In your case you do:

if (strpos($data_go, "/") !== false) {
    $date_exploded = explode("/", $data_go);
    if (checkdate($date_exploded[1], $date_exploded[2], $date_exploded[0])) {
        return TRUE;
    } else {
        return FALSE;
    }
} else {
    return FALSE;
}


Are you trying to match all possible dates? As @nomulous pointed out, the pattern matches mm/dd/yyyy, not yy/mm/dd. I'd go with checkdate to verify the date, and use \d in place of [0-9] for simplicity.


The following regex matches your date and others like it.

([1-9][\d]{3})[- \/.]([0-1][\d])[- \/.]([0-3][\d])

Explanation

The first group ([1-9][\d]{3}) is the year and allows for the range 1000 to 9999

The second group ([0-1][\d]) is the month and allows for the range 00 to 19 (obviously it won't catch bad months)

The third group ([0-3][\d]) is the day and allows for the range 00 to 39 (again, it won't catch bad days)

Once you have those parts you can do explicit validation using more appropriate tools than regex, or just use a DateTime object to start with, and don't reinvent the wheel.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号