How to Validate Date String in PHP

Before taking any action with date input, it always a great idea to validate the date string. Date validation helps to check whether the provided string is a valid date format. Using the DateTime class you can easily check if the date string is valid in PHP.

In the example code snippet, we will show you how to validate a date string in PHP. It is very useful for server-side validation of the date input 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