How to Validate Date String in PHP

Before performing any operation with a date input, it is always a good idea to validate the date string. Date validation ensures that the provided string follows a valid date format. Using the DateTime class in PHP, you can easily check whether a date string is valid.

In the following example code snippet, we will demonstrate how to validate a date string in PHP. This approach is very useful for performing server-side validation of date inputs using PHP.

The validateDate() function checks whether the given string is a valid date using PHP. It uses PHP DateTime class to validate date based on the specified format. This function returns TRUE if date string is valid, otherwise FALSE.

  • $date – Required. The date string to validate.
  • $format – Optional. The format of the date string.
function validateDate($date$format 'Y-m-d'){
    
$d DateTime::createFromFormat($format$date);
    return 
$d && $d->format($format) === $date;
}

Call the validateDate() function and pass the date string in the first parameter.

// Returns false
var_dump(validateDate('2018-14-01')); 
var_dump(validateDate('20122-14-01'));
var_dump(validateDate('2018-10-32'));
var_dump(validateDate('2017-5-25'));

// Returns true
var_dump(validateDate('2018-12-01'));
var_dump(validateDate('1970-11-28'));

By default, the format is set to Y-m-d. If you want to allow day and month without leading zeroes, specify the respective format (Y-n-j).

// Returns true
var_dump(validateDate('2018-2-5''Y-n-j'));

3 Comments

  1. ‪3dol‬‏ Said...
  2. James Said...
  3. Robin Singh Said...

Leave a reply

keyboard_double_arrow_up