Date validation

I want validate time in format Y-m-d to save it in my db. I tried my codes below, and I get stuck on it.


 $date = mysql_real_escape_string (strtolower($_POST['date']))."<br/>";
 $format = date('Y-m-d', strtotime('$date'));
  if ($format == TRUE) { echo 'yes'; }  else{ echo 'no'; } 


BTW, when the user type the word ‘today’, it will automatically refer to the current date in the same format and I got it working, now I’m having trouble for combining the validation above. here is my code


if ($date == 'today') {
echo date("Y-m-d");
}

Thank you in advance!

Try something like this…

<?php

# Fetch the date from the post array, or default to today
$date = isset($_POST['date']) ? $_POST['date'] : 'today';

# Convert the provided date to a time stamp
$timestamp = strtotime($date);

# If the provided date could not be converted to a time stamp, default to the current date & time
if(empty($timestamp))
{
    $timestamp = time();
}

# Format the timestamp to your desired date format
$formatted_date = date("Y-m-d", $timestamp);

?>

thank you for your quick response, I appreciate the default value, its cool…
What if I will not accept (special)characters or a like, or Feb.30 input…

is that possible?

You mention validating, I think, what is $_POST[‘date’] typically supposed to contain?

show us the result of a typical submission where you do this first on your form handling PHP script


<?php
var_dump( $_POST['date'] );


... rest of your script

If you want to validate the date, convert it into UNIX value using strtotime() and then calculate if it’s between the two desired range dates. If it is, then convert it from the UNIX code into the format you want to store in your database. This way, you’re guaranteed to have the same date format as a result every time.

As JV started:

<?php 

# Fetch the date from the post array, or default to today 
$date = isset($_POST['date']) ? $_POST['date'] : 'today'; 

# Convert the provided date to a time stamp 
$timestamp = strtotime($date); 

# If the provided date could not be converted to a time stamp, default to the current date & time 
if(empty($timestamp)) 
{ 
    $timestamp = time(); 
} else {
    if( $timestamp > strtotime('18 years ago') ){
        echo "Sorry, but you must be 18 years old to view this website";
        exit;
    }
}

# Format the timestamp to your desired date format 
$formatted_date = date("Y-m-d", $timestamp); 

?>

The first step to nip this common problem in the bud is not give the user arbritrary inputs. Use combo boxes.


<select name="date[month]">
  <option value=""></option>
  <option value="01">January</option>
  ...
</select>
</select name="date[day]">
...
</select>
<select name="date[year]">
</select>

Now PHP can expect an array within the post or get array called ‘date’. The check is now stupid simple



if (is_array($_POST['date']) && checkdate( (int) $_POST['date']['month'], (int) $_POST['date']['day'], (int) $_POST['date']['year'] ) ) {


If you’re real paranoid, make sure the leading zero is attached to month and day - though you can make this part of the value of the options in the select as shown above.


if (strlen($_POST['date']['month']) == 1) {
  $_POST['date']['month'] = '0'.$_POST['date']['month'];
}

And the same code for the day. Note that the only way this correction actually executes if someone is submitting to your page with their own form - a normal user doesn’t face this problem. This does protect the database from bad inputs.

While select boxes feel clumsy if you’re on keyboard and mouse - they are easier to deal with. Even easier is the date picker html 5 tool - but at the moment only Opera implements this.

I’m making this whole thing for firefox users. I’m using opera by default, I’m just trying to validate the input in firefox just in case there will be a wrong input from other browser when somebody make a pun of my system then I can guard my db from that.

In that event run a javascript that emulates HTML 5 inputs for most browsers (Opera alone supports input type=“date” at the moment). You’ll can split the string on ‘-’ and then pass the three resulting numbers to checkdate as in my example above. The goal remains the same - avoid arbritrary input from users when possible.

sounds good to me, but I am still a novice, practicing php I don’t know how to do your suggestion…sounds new to me .

If you want pure PHP solution you could try to make the formular like this:

<form method="POST">
	Day:
	<select name="day">
	<?php for ($i = 1; $i <= 31; $i++) : ?>
		<option value="<?= $i ?>"><?= $i ?></option>
	<?php endfor ?>
	</select>
	Month:
	<select name="month">
	<?php for ($i = 1; $i <= 12; $i++) : ?>
		<option value="<?= $i ?>"><?= $i ?></option>
	<?php endfor ?>
	</select>	
	Year:
	<select name="year">
	<?php for ($i = 1990; $i <= date('Y'); $i++) : ?>
		<option value="<?= $i ?>"><?= $i ?></option>
	<?php endfor ?>
	</select>
	<input type="submit" value="submit" name="submit" />
</form>

<?php
if (!empty($_POST)){
	if (checkdate($_POST['month'], $_POST['day'], $_POST['year'])){
		$timestamp = mktime(0, 0, 0, $_POST['month'], $_POST['day'], $_POST['year']);
		$date = date('Y-m-d', $timestamp);
		echo $date; // Your SQL query goes here
	}
	else {
		echo 'Incorrect date format.';
	}
}
?>

If you want a nicer solution then I recommend using jQuery UI datepicker http://jqueryui.com/demos/datepicker/ .

cool…thank you, i’ll try this…does it have any conflict with html5 input date attribute?

It replaces it in a manner that will work across all browsers. You cannot safely use <input type=“date”> because the majority of browsers do not support webforms 2.0. If you do want to use them you must use javascript extensions which emulate the behaviors of those objects.

using checkdate :tup: