I\'m trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I
It all depends on how strict you want this function to be. For instance, if you don't want to allow months above 12 and days above 31 (not depending on the month, that would require writing date-logic), it could become pretty complicated:
function checkDate($date)
{
$regex = '/^' .
'(' .
// Allows years 0000-9999
'(?:[0-9]{4})' .
'\-' .
// Allows 01-12
'(?:' .
'(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
'(?:11)|(?:12)' .
')' .
'\-' .
// Allows 01-31
'(?:' .
'(?:01)|(?:02)|(?:03)|(?:04)|(?:05)|(?:06)|(?:07)|(?:08)|(?:09)|(?:10)|' .
'(?:11)|(?:12)|(?:13)|(?:14)|(?:15)|(?:16)|(?:17)|(?:18)|(?:19)|(?:20)|' .
'(?:21)|(?:22)|(?:23)|(?:24)|(?:25)|(?:26)|(?:27)|(?:28)|(?:29)|(?:30)|' .
'(?:31)' .
')' .
'$/';
if ( preg_match($regex, $date) ) {
return true;
}
return false;
}
$result = checkDate('2012-09-12');
Personally I'd just go for: /^([0-9]{4}\-([0-9]{2}\-[0-9]{2})$/
Function to validate generic date format:
function validateDate($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
Example of execution:
var_dump(validateDate('2021-02-28')); // true
var_dump(validateDate('2021-02-29')); // false
Try this.
$date="2012-09-12";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
return true;
} else {
return false;
}
If it is of any help, here is a regex for j-n-Y format (year has to be greater than 2018):
if (preg_match('/^([1-9]|[1-2][0-9]|[3][0-1])\-([1-9]|[1][0-2])\-(?:20)([1][8-9]|[2-9][0-9])$/', $date)) {
// Do stuff
}
preg_match needs a / or another char as delimiter.
preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$date)
you also should check for validity of that date so you wouldn't end up with something like 9999-19-38
bool checkdate ( int $month , int $day , int $year )
You could also do it like this:
if (DateTime::createFromFormat('Y-m-d', $date)->format('Y-m-d') === $date) {
// date is correctly formatted and valid, execute some code
}
This will not only check the format, but also the validity of the date self, since DateTime
will create only valid dates and this needs to match the input.