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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With