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?
The checkdate() function is used to validate a Gregorian date.
The date validator requires day, month and year. If you are looking for hour and time validator, HH:mm , for example, you should use the regexp validator. Below are some example of possible formats: YYYY/DD/MM.
MySQL date/time Functions. The date() function is used to get the date from given date/datetime. The adddata() function is used to get the date in which some time/date intervals are added. The curdate() function is used to get the current date.
I am using this function:
<?php
function validateMysqlDate( $date ){
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $date, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
// check it:
$a = validateMysqlDate('2012-12-09 09:04:00');
$b = validateMysqlDate('20122-12-09 09:04:00');
$c = validateMysqlDate('2012-12_09 09:04:00');
$d = validateMysqlDate('');
var_dump( $a );
var_dump( $b );
var_dump( $c );
var_dump( $d );
?>
$a is true, the others are false - and that is correct
The function from Raveren (above) will not cover valid dates with timestamps !!! $a returns false there! And btw: checkdate() would return true for $b although it is not a valid mysql datetime
I personally found this to be the correct and elegant way to determine if the date is both according to format and valid:
20111-03-21
as invalid - unlike checkdate()
explode()
solutionsDATE
format (10.03.21 is the same as 2010-03-21)Here's the method you can use:
/**
* Tests if a string is a valid mysql date.
*
* @param string date to check
* @return boolean
*/
function validateMysqlDate( $date )
{
return preg_match( '#^(?P<year>\d{2}|\d{4})([- /.])(?P<month>\d{1,2})\2(?P<day>\d{1,2})$#', $date, $matches )
&& checkdate($matches['month'],$matches['day'],$matches['year']);
}
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