[php] php date validation

Im trying to to set up a php date validation (MM/DD/YYYY) but I'm having issues. Here is a sample of what I got:

$date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%'; 

$test_date = '03/22/2010'; 
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
    $errors[] = 'user name most have no spaces';`

This question is related to php validation date

The answer is


This function working well,

function validateDate($date, $format = 'm/d/Y'){
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

You can use some methods of the DateTime class, which might be handy; namely, DateTime::createFromFormat() in conjunction with DateTime::getLastErrors().

$test_date = '03/22/2010';

$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
    $errors[] = 'Some useful error message goes here.';
}

This even allows us to see what actually caused the date parsing warnings/errors (look at the warnings and errors arrays in $date_errors).


Not sure if this answer the question or going to help....

$dt = '6/26/1970' ; // or // '6.26.1970' ;

$dt = preg_replace("([.]+)", "/", $dt);

$test_arr  = explode('/', $dt);

if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))

     { echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }

   else

     { echo "no good...format must be in mm/dd/yyyy"; }

Nicolas solution is best. If you want in regex,

try this,

this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators

(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}

Instead of the bulky DateTime object .. just use the core date() function

function isValidDate($date, $format= 'Y-m-d'){
    return $date == date($format, strtotime($date));
}

REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php


I know this is an older post, but I've developed the following function for validating a date:

function IsDateTime($aDateTime) {
    try {
        $fTime = new DateTime($aDateTime);
        $fTime->format('m/d/Y H:i:s');
        return true;
    }
    catch (Exception $e) {
        return false;
    }
}

I think it will help somebody.

function isValidDate($thedate) {
    $data = [
        'separators' => array("/", "-", "."),
        'date_array' => '',
        'day_index' => '',
        'year' => '',
        'month' => '',
        'day' => '',
        'status' => false
    ];

    // loop through to break down the date
    foreach ($data['separators'] as $separator) {
        $data['date_array'] = explode($separator, $thedate);
        if (count($data['date_array']) == 3) {
            $data['status'] = true;
            break;
        }
    }

    // err, if more than 4 character or not int
    if ($data['status']) {
        foreach ($data['date_array'] as $value) {
            if (strlen($value) > 4 || !is_numeric($value)) {
                $data['status'] = false;
                break;
            }
        }
    }

    // get the year
    if ($data['status']) {
        if (strlen($data['date_array'][0]) == 4) {
            $data['year'] = $data['date_array'][0];
            $data['day_index'] = 2;
        }elseif (strlen($data['date_array'][2]) == 4) {
            $data['year'] = $data['date_array'][2];
            $data['day_index'] = 0;
        }else {
            $data['status'] = false;
        }
    }

    // get the month
    if ($data['status']) {
        if (strlen($data['date_array'][1]) == 2) {
            $data['month'] = $data['date_array'][1];
        }else {
            $data['status'] = false;
        }
    }

    // get the day
    if ($data['status']) {
        if (strlen($data['date_array'][$data['day_index']]) == 2) {
            $data['day'] = $data['date_array'][$data['day_index']];
        }else {
            $data['status'] = false;
        }
    }

    // finally validate date
    if ($data['status']) {
        return checkdate($data['month'] , $data['day'], $data['year']);
    }

    return false;
}

Use it:

function validate_Date($mydate,$format = 'DD-MM-YYYY') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);       

    if (is_numeric($year) && is_numeric($month) && is_numeric($day))
        return checkdate($month,$day,$year);
    return false;           
}         

We can use simple "date" input type, like below:

Birth date: <input type="date" name="userBirthDate" /><br />

Then we can link DateTime interface with built-in function 'explode':

public function validateDate()
    {
        $validateFlag = true;
        $convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
        $birthDateErrors = DateTime::getLastErrors();

        if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
        {
            $_SESSION['wrongDateFormat'] = "The date format is wrong.";
        }

        else
        {
            $testBirthDate = explode('-', $this->birthDate);
            if ($testBirthDate[0] < 1900)
            {
                $validateFlag = false;
                $_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
            }
        }

        return $validateFlag;
    }

I tested it on Google Chrome and IE, everything works correctly. Furthemore, Chrome display simple additional interface. If you don't write anything in input or write it in bad format (correctly is following: '1919-12-23'), you will get the first statement. If you write everything in good format, but you type wrong date (I assumed that nobody could born before XX century), your controller will send the second statement.


Try This

/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/

this regular expression valid for :

  • 2017-01-01T00:00:00+0000
  • 2017-01-01 00:00:00+00:00
  • 2017-01-01T00:00:00+00:00
  • 2017-01-01 00:00:00+0000
  • 2017-01-01

Remember that this will be cover all case of date and date time with (-) character


Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?