Date Format Validation In PHP
Date format validation in PHP is important to ensure that input date values are in the correct format before they are used or stored.
In this post we will see how to validate date in PHP. If the input date does not match the specified format, the function will return 'false'. You can then use this result to trigger an error message or other appropriate action in your code.
Date that you want to test may have various Formats Like:
- YYYY-MM-DD
- DD/MM/YYYY
- MM-DD-YYYY
- DD-MM-YYYY
- YYYY-MM-DD and so on.
We will see mostly used formats. Date in the other format can easily be validated by making small changes in the existing code. So, let’s have look at them.
YYYY-MM-DD Format
//Date that needs to be tested goes here
$date = '2013-05-14';
function isItValidDate($date) {
if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
}
if (isItValidDate($date)) {
echo 'It’s a valid Date. ';
} else {
echo 'Entered Date is invalid..!!';
}
DD/MM/YYYY Format
//Date that needs to be tested goes here
$date = '14/05/2013';
function isItValidDate($date) {
if (preg_match("/^(\d{2})\/(\d{2})\/(\d{4})$/", $date, $matches)) {
if (checkdate($matches[2], $matches[1], $matches[3])) {
return true;
}
}
}
if (isItValidDate($date)) {
echo 'It’s a valid Date';
} else {
echo 'Entered Date is invalid..!!';
}
MM-DD-YYYY Format
//Date that needs to be tested goes here
$date = '05-14-2013';
function isItValidDate($date) {
if (preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches)) {
if (checkdate($matches[1], $matches[2], $matches[3])) {
return true;
}
}
}
if (isItValidDate($date)) {
echo 'It’s a valid Date';
} else {
echo 'Entered Date is invalid..!!';
}