Monday, 3 February 2014

PHP Date Validation

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to checkdate.

<?php
    /**
    *
    * Validate a date
    *
    */
    function validateDate( $date, $format='YYYY-MM-DD')
    {
        switch( $format )
        {
            case 'YYYY/MM/DD':
            case 'YYYY-MM-DD':
            list( $y, $m, $d ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYY/DD/MM':
            case 'YYYY-DD-MM':
            list( $y, $d, $m ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'DD-MM-YYYY':
            case 'DD/MM/YYYY':
            list( $d, $m, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'MM-DD-YYYY':
            case 'MM/DD/YYYY':
            list( $m, $d, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYYMMDD':
            $y = substr( $date, 0, 4 );
            $m = substr( $date, 4, 2 );
            $d = substr( $date, 6, 2 );
            break;

            case 'YYYYDDMM':
            $y = substr( $date, 0, 4 );
            $d = substr( $date, 4, 2 );
            $m = substr( $date, 6, 2 );
            break;

            default:
            throw new Exception( "Invalid Date Format" );
        }
        return checkdate( $m, $d, $y );
    }


   echo validateDate( '2007-04-21' ) ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY-DD-MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY/DD/MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '21/4/2007', 'DD/MM/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '4/21/2007', 'MM/DD/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '20070421', 'YYYYMMDD' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '04212007', 'YYYYDDMM' )  ? 'good'. "\n" : 'bad' . "\n";

?>

No comments:

Post a Comment