Date validation in PHP
In this post we will see how to validate date in PHP. 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 = '2013-05-14';
//Date that needs to be tested goes here
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 = '14/05/2013';
//Date that needs to be tested goes here
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 = '05-14-2013';
//Date that needs to be tested goes here
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..!!';
}
Comments
Post a Comment