Users would select their date from 3 dropdowns (day, month, year). I will combine them on server-side to make a string like '2008-12-30'. How can I then validate to make sure this date was in the right format/numeric only, etc?
You can check that the date is valid using checkdate. If you want to make sure that the values are numeric and the correct length, you could do something as simple as an is_int ctype_digit and a strlen combination before you build the date.
// untested
if( !ctype_digit)( $month ) || strlen( $month ) != 2 ) {
// handle error
}
// repeat for $day and $year
if ( checkdate( $month, $day, $year ) {
// do your work
}
If they are 3 separate drop-downs, you will need to validate them as three separate values.
Ie,
- Validate that the year column is numeric and between whatever years are valid in your app
- Validate that the month column is numeric
- Validate that the day column is numeric
- Validate that they are all valid values using checkdate()
Or, you could just cast them all to integer, combine them together into a date, and see if the resulting date is valid. Ie,
$time = mktime(0, 0, 0, (int)$_POST['month'], (int)$_POST['day'], (int)$_POST['year']);
// in this example, valid values are between jan 1 2000 (server time) and now
// modify as required
if ($time < mktime(0, 0, 0, 1, 1, 2000) || $time > time())
return 'Invalid!';
$mysqltime = date('Y-m-d', $time);
// now insert $mysqltime into database
The downside to this method is that it'll only work with dates within the Unix timestamp range ie 1970 to 2038 or so.
If you have three dropdowns then the values coming from the dropdowns should always be numbers since you control the values associated with the month (shown below). This would then lead to the conclusion that the combined result is valid.
<option value="01">January</option>
If you provide provide assistance entries in the drop downs such as "Select a Month" then you can make that value 0 and ensure that the values coming from each drop box is greater than zero.
There is the possibility that someone will alter the HTML form to provide other values. If this is a concern then you can use the PHP function ctype_digit() to check that each value provided is actually a numerical digit.
If your concern is that the date is actually valid the use the checkdate() function.