我有一个输入文本框,让最终用户填写他们执行检查的日期。当通过表单提交存储在数据库中时,我希望格式化为MM/DD/YYYY的日期。
我尝试过使用preg_match函数对其进行regex检查,但对于否则命令或if命令,我有一些不太正确的地方。它仍然允许04-05-2019提交,而不是停止提交。任何帮助都将不胜感激!
//check inspection date format with regex
$date_check_regex = "/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[-
\/.](19|20)\d\d/";
// Validate inspection date
$cust_inspection_date = trim($_POST["cust_inspection_date"]);
if(empty($cust_inspection_date)){
$cust_inspection_date_err = "Please enter the customers Inspection Date.";
} elseif(!filter_var($cust_inspecton_date, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
if(preg_match($date_check_regex, $cust_inspection_date)) {
$cust_inspection_date = $cust_inspection_date;
} else {
$cust_inspection_date_err = "Please enter a valid inspection date MM/DD/YYYY.";
}
} 我试过了
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
//check inspection date regex check
$date_check_regex = "/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/";
// Validate inspection date
$cust_inspection_date = trim($_POST["cust_inspection_date"]);
if(empty($cust_inspection_date)){
$cust_inspection_date_err = "Please enter the customers Inspection Date.";
if(!filter_var($cust_inspecton_date, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))),
if(preg_match($date_check_regex, $cust_inspection_date)) {
$cust_inspection_date = $cust_inspection_date;
} else {
$cust_inspection_date_err = "Please enter a valid inspection date MM/DD/YYYY.";
// $cust_inspection_date = $cust_inspection_date;
}
}发布于 2019-04-06 02:41:54
看起来它允许04 - 05-2019格式,因为您使用的是- \/.,它允许字符-、/和。供人使用。
如果要求它仅为/,则需要删除。还有-
(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)\d\d发布于 2019-04-06 03:37:23
使用正则表达式解析日期的问题是,它将允许非法日期(例如02/30/2019)通过。通常最好使用内置的日期解析工具并验证日期是否有效。例如,为了只允许MM/DD/YYYY格式中的日期,您可以这样做。
$cust_inspection_date = trim($_POST["cust_inspection_date"]);
$date = date_create_from_format('m/d/Y', $cust_inspection_date);
if (!$date || $date->format('m/d/Y') != $cust_inspection_date) {
echo "$cust_inspection_date is invalid\n";
}
else {
echo "$cust_inspection_date is valid\n";
}https://stackoverflow.com/questions/55545210
复制相似问题