I have small problem with date validation. It works if it only validates a day, not the whole date.
If, today is 21.07.2015, validation enables dates before the 21st of each month/each year. It should accept only dates starting from today.
Code is here:
if (empty ($_POST['data'])) {
$data_error = "You need to type a date";
++$error_counter;
} elseif ($_POST['data'] < date("d.m.Y")) {
$data_error = "You have chosen incorrect date";
++$error_counter;
} else {
$data = $_POST['data'];
}
You can compare by strtotime()
if (empty ($_POST['data'])) {
$data_error = "You need to type a date";
++$error_counter;
} elseif (strtotime($_POST['data']) < strtotime(date("d.m.Y"))) {
$data_error = "You have chosen incorrect date";
++$error_counter;
} else {
$data = $_POST['data'];
}
Related
This question already has answers here:
why string is greater or less than the integer?
(3 answers)
Closed 3 years ago.
I have this function to validate the date of birth and send back error message when date is correct or not.
Here is my function
function checkBirthDate($string)
{
$matches = array();
$pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
if (!preg_match($pattern, $string, $matches)) return false;
if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
return true;
}
//Get Parameters Passed From the JS Call to This Script
$fieldValue = $_GET["q"];
$fieldName = $_GET["q2"];
$fieldCheckBox = $_GET["q3"];
//Validate the DOB
if ($fieldName == 'stepbirth') {
$response = "";
foreach (explode(",", $fieldValue) as $dateString) {
//echo $dateString;
$birthDateLen = strlen($dateString);
if ($dateString > 9) {
if (checkBirthDate($dateString)) {
//Get last 4 characters of the Date for the Year
$year = substr($dateString, -4);
if ($year > 1900) {
//Get Timestamp passed over
$dt = DateTime::createFromFormat('d/m/Y', $dateString);
$userDate = $dt->getTimestamp();
//Get Date 1 Year from Today
$yearTime = date(strtotime('+100 year'));
//If User's Date is Within 1 Year
if ($userDate < $yearTime) {
$response .= '{"code":1,"message":""},';
} else {
$response .= '{"code":0,"message":"Fill date till 365 from now"},';
}
} else {
$response .= '{"code":0,"message":"Fill date after 1900"},';
}
} else {
$response .= '{"code":0,"message":"Fill valid date in."},';
}
} else {
$response .= '{"code":0,"message":""},';
}
}
$response = substr($response, 0, -1);
echo "[" . $response . "]";
}
Which is working fine and sending the correct response, but it has only one issue, while date starts at 0 like 01,02,03 till 09. It does not validate it always sends response code "0" and do not show error message in response, even the complete date of birth is not correct like 01/20/2018 here month is not correct. But when date starts 11/20/2018 it does correct validation and sends response code "1" and shos the message.
Can anyone help with this what I am doing wrong here?
Why not using strtotime for you value?
PHP will try to convert the date for you.
By using date("Y", strtotime($dateString)) returns the year for you. In your case you can use the time to validate or do your things with the date.
Further by using json_encode() you can pass an array which results in an json response. So:
$response = array("code" => 1, "message" => "Just a message");
$actual = json_encode($response);
echo $actual; //Returns { "Code": 1, "Message": "Just a message" }
This is what I am after here. If the checkbox is checked, then I want to assign these values
$begindate = '20160101';
$enddate = '20161231'
If the checkbox is NOT checked then I want to force the user to select from the date selectors, and if either date is null then throw an error. I have this syntax, and the issue I am having with it is that if the check box is checked AND the user inputs dates then the input dates over-write the checkbox dates. NOT what I want to happen. There may be other syntax flaws in here that my new self has not realized yet, but what needs to be changed in this syntax in order to make it flow properly and execute as I describe above?
<body>
<form>
Display 2016 Data? <input type = 'Checkbox' Name='twentysix' value="twentysix"><br>
<input type="submit" name="submit" value="Gather">
</form>
</body>
<?php
if (isset($_POST['submit']))
{
if ( isset($_POST['twentysix']) ) {
$begindate = '20160101';
$enddate = '20161231'
} else {
$begindate = $begindate;
$enddate = enddate;
}
$begindateerror = false;
$enddateerror = false;
if (empty($_POST['begindate'])) {
$begindateerror = true;
}
if (empty($_POST['enddate'])) {
$enddateerror = true;
}
if ($begindateerror) {
echo "<strong>Please select a start date.</strong><br>";
} else if ($enddateerror) {
echo "<strong>Please select a end date.</strong><br>";
} else {
$begindate = $_POST['begindate'];
$enddate = $_POST['enddate'];
}
}
Move your if statements for the checkbox to the end
$begindateerror = false;
$enddateerror = false;
if (empty($_POST['begindate'])) {
$begindateerror = true;
}
if (empty($_POST['enddate'])) {
$enddateerror = true;
}
if ($begindateerror) {
echo "<strong>Please select a start date.</strong><br>";
} else if ($enddateerror) {
echo "<strong>Please select a end date.</strong><br>";
} else {
$begindate = $_POST['begindate'];
$enddate = $_POST['enddate'];
}
if ( isset($_POST['twentysix']) ) {
$begindate = '20160101';
$enddate = '20161231'
} else {
$begindate = $begindate;
$enddate = enddate;
}
Note: This is not the best way to do it. I would recommend moving the begin/end date code into the else statment of the checkbox
I'm trying to validate dates in PHP, but the problem is that with some dates work, an example would be: "02/2/2015" returns true, "20/12/2015" false returns, is a serious problem and I see no error in the code.
Function.
<?php
function check_date($date) {
$open_date = explode('/', $date);
if (count($open_date) == 3) {
if (checkdate($open_date[0], $open_date[1], $open_date[2])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//$date = "02/2/2015"; // return true !
$date = "20/12/2015"; // return false ?
if(check_date($date)) {
echo "valid";
} else {
echo "invalid";
}
?>
How could solve this problem?
checkdate expects a month, day and year, in that order:
https://secure.php.net/manual/en/function.checkdate.php
If your dates are formatted as day/month/year then you can still use checkdate, you'll just have to change the order of the parameters:
if (checkdate($open_date[1], $open_date[0], $open_date[2]))
The signature of checkdate function looks like checkdate(month,day,year); . You can have upto 12 months and not 20. :-)
I am creating a web form for my work which is being validated using PHP. However, when I test the page I keep getting all of my error messages returned without the form being submitted properly when valid information is inputted. The following is a small section of the code (including the HTML sections).
<?php
$date =""
$dateerror = ""
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$dateerror = "Date is required";
} else {
$date = test_input($_POST["date"]);
$array = explode("/", $date);
$day = $array[1];
$month = $array[0];
$year = $array[2];
if (!checkdate($month, $day, $year)) {
$dateerror = "Date mustbe in M/D/Y format";
} else {
date_default_timezone_set("America/Anchorage");
$today = strtotime("now");
if (strtotime($date)>=$today) {
$date = test_input($_POST["date"]);
} else {
$dateerror = "Date is before present day";
}
}
}
<input type="text" size="9" name="date" id="date" required title="Please enter current date"><?php echo $dateerror; ?><br>
Again, the PHP code just returns "Date is before present day" even when the date is the current date.
If you want to validate a date in PHP, the best way to do it is to use the DateTime class, and specifically the createFromFormat method.
This call will create a DateTime object set to the specified date in the given format, or false if it was an invalid date.
So for example:
<?php
$input = "05/08/2015";
$test = DateTime::createFromFormat('d/m/Y', $input);
if (!$test) {
print "You entered an invalid date";
die;
}
$now = new DateTime();
if ($test < $now) {
print "Date is before present.";
die;
}
?>
Simple as that. There's no need for regex, or for exploding the input, etc; just a single simple test. And you can also then use the $test variable to process the date as well once you've determined that it's valid, since it's a standard DateTime object.
[EDIT] I've added a bit in the code to deal with using the DateTime class to handle date comparisons, to give the 'before present' error.
The important point here is that if you have a DateTime object, you need to compare it with another DateTime object; the older strtotime() produces a different type of date resource to DateTime, and you can't use them together (at least not without converting between them all the time).
The solution: use date("M/D/Y"):
$today = strtotime(date("M/D/Y")); // 1432958400
$date = strtotime($_POST["date"]); // user input. 05-30-2015 will yield 1432958400
// the rest of your logic here
Here's the code specific solution:
<?php
$date =""
$dateerror = ""
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$dateerror = "Date is required";
} else {
$date = test_input($_POST["date"]);
$array = explode("/", $date);
$day = $array[1];
$month = $array[0];
$year = $array[2];
if (!checkdate($month, $day, $year)) {
$dateerror = "Date mustbe in M/D/Y format";
} else {
date_default_timezone_set("America/Anchorage");
$today = strtotime(date("M/D/Y"));
if (strtotime($date)>=$today) {
$date = test_input($_POST["date"]);
} else {
$dateerror = "Date is before present day";
}
}
}
<input type="text" size="9" name="date" id="date" required title="Please enter current date"><?php echo $dateerror; ?><br>
I'm working on a final project for a PHP class and I'm having trouble with validating the code. In the else if part of the code I always get an error at both of these else if statements and the application stops processing.
The code below is a part of a .php file that has a HTML form for setting reminders.
} else if (!checkdate($_POST['reminderMonth'],$_POST['reminderDate'],$_POST['remindereEar'])) {
$error_message = "Selected date does not exist.";
} else if ($reminderDate <= $t_date) {
$error_message = "Selected date has already occured.";
All of the code:
if(isset($_POST['submit'])) {
//get data
$t_date = date(Ymd);
$year = $_POST['reminderYear'];
$month = $_POST['reminderMonth'];
$day = $_POST['reminderDay'];
//validate data
$reminderDate = $year.$month.$day;
if (empty($_POST['reminderName'])) {
$error_message = "Name is a required field.";
} else if (!checkdate($_POST['reminderMonth'],$_POST['reminderDate'],$_POST['remindereEar'])) {
$error_message = "Selected date does not exist.";
} else if ($reminderDate <= $t_date) {
$error_message = "Selected date has already occured.";
} else {
$error_message = ''; }
//redirect
if(empty($error_message)) {
mysql_query("INSERT INTO reminder_event
(reminderName,reminderDescript,reminderDate)
VALUES
('{$reminderName}','{$reminderDescript}','{$reminderDate}')");
header("Refresh: 1;url=reminder_list.php");
} else {
echo($error_message); } }
date(Ymd) will produce error should be
date('Y m d');
and make sure $reminderDate = $year.$month.$day; is formatted in the same way
$reminderDate = $year.' '.$month.' '.$day;
Also 2 typos:
$_POST['reminderDate'],$_POST['remindereEar']
Dont know if this is a solution, but still looks like it will cause problems if you run it your way
I see 2 typos:
$_POST['reminderDate'],$_POST['remindereEar']
It should be:
$_POST['reminderDay'],$_POST['reminderYear']
You made a mistake with reminderDate and remindereEar.
It should be instead : $_POST['reminderDay'], $_POST['reminderYear']
Tell me if you get more error after changing that.