如果输入结束日期超过输入开始日期的3天,如何验证用户?
鉴于:PHP代码
if(isset($_POST['btnRequest']))
{
$leaveFrom = $_POST['leaveFrom'];
$leaveTo = $_POST['leaveTo'];
}
$sql_insert = "INSERT INTO leaves (leaveFrom, leaveTo) VALUES (?, ?)";
HTML Code
<input type="date" id="leaveFrom" name="leaveFrom" class="form-control" required="true" />
<input type="date" id="leaveTo" name="leaveTo" class="form-control" required="true" />
数据类型是Microsoft SQL的“日期”
目标:如果日期范围为3天或更短,则提交日期。
(这适用于可以向管理员提交他/她的“病假”且限制为3天的用户)
我尝试了Zain Farooq的代码,但这是我尝试过的。
function fourDays()
{
return date("Y-m-d"),strtotime("+ 4days"));
}
$date = date('Y-m-d'),strtotime($leaveTo)); // I want to
validate the input from the input 'leaveFrom' but I have no idea how
if($date >= fourdays())
{
$dispMsg = $dateerrorMsg;
}
使用此代码比较两个日期
function today()// it will get date of today
{
return date("Y-m-d");
}
function last_three_day()//it will get date of last third day
{
return date("Y-m-d",strtotime("-3 days"));
}
$date = date('Y-m-d',strtotime('2018-03-01')); //it is your date which you want to compare
if($date >= last_three_day() && $date <= today())
{
echo "yes";
}
更新 实际上你错过了一些逻辑。你比较了两个错误的日期。您必须在用户输入日期之间做出改变,然后您才能获得真实的结果
<?php
if(isset($_POST['submit']))
{
$leaveFrom = date_create($_POST['leaveFrom']);
$leaveTo = date_create($_POST['leaveTo']);
$dayDifference = date_diff($leaveFrom, $leaveTo)->format('%d');
$yearDifference = date_diff($leaveFrom, $leaveTo)->format('%y');
$monthDifference = date_diff($leaveFrom, $leaveTo)->format('%m');
/*These conditions will check the year and month differences too.*/
if($yearDifference==0)
{
if($monthDifference==0)
{
if($dayDifference<=4 && $dayDifference>0)
{
echo "Eligible";
}
else//else for day difference
{
echo "Not Eligible";
}
}
else
{
echo "Not Eligible";
}//else for month difference
}
else
{
echo "Not Eligible";
}//else for year difference
}
?>
<html>
<body>
<form action="" method="post">
<label for="leaveFrom">Leave From</label> <input type="date" name="leaveFrom"><br>
<label for="leaveTo">Leave To</label><input type="date" name="leaveTo"><br>
<br> <input type="submit" name="submit">
</form>
</body>
</html>
找到了解决方案。非常感谢Zain Farooq!
if(isset($_POST['btnRequest']))
{
$leaveReason = $_POST['leaveReason'];
$leaveFileDate = $_POST['leaveFileDate'];
$leaveFrom = date_create($_POST['leaveFrom']);
$leaveTo = date_create($_POST['leaveTo']);
$dayDifference = date_diff($leaveFrom, $leaveTo)->format('%d');
if($dayDifference<=4)
{
$sql_insert = "INSERT INTO leaves (leaveReason, leaveFileDate, leaveFrom, leaveTo, leaveStatus, accountID, ltypeID)
VALUES(?, ?, ?, ?, ?, ?, ?)";
$params_insert = array($leaveReason, $leaveFileDate, $leaveFrom, $leaveTo, 'Pending for Approval', $accID, $ltypeID);
$stmt_insert = sqlsrv_query($con, $sql_insert, $params_insert);
if($stmt_insert === false) {
#die(print_r(sqlsrv_errors(), true));
$dispMsg = $errorMsg;
}
else
{
$dispMsg = $successMsg;
}
}
else
{
$dispMsg = $dateerrorMsg;
}