In this article, we will see how to validate a date string format in PHP.

Before validating the date string format first we have to make sure the format that the date string should be in. There are several date formats available. You can refer to the following documentation to understand more about the date string formats.

Date string formats php documentation

Using the DateTime:

Once the format of the date string is determined, then we can use the DateTime::createFromFormat() function to create a DateTime object from the date string. This function takes two parameters: the format of the date string and the date string itself.

Following is an example of using the createFromFormat( ) which validates the datestring in the format of ‘YYYY-MM-DD’:

$dateString = '2023-03-26';
$dateFormat = 'Y-m-d';
$dateTimeObj = DateTime::createFromFormat($dateFormat, $dateString);

if (!$dateTimeObj) {
    echo "Invalid date string format";
} else {
    echo "Valid date string format";
}

Explanation:

In the above example, we first define the date string $dateString and the format of the date string $dateFormat and use the DateTime::createFromFormat() function to create a DateTime object from the date string using the specified format.

If the date string is not in the correct format, this function will return false and then we use an if statement to check if the function returned false/true and show an error if it returns false.

If the date string is in the proper format then it returns the valid date object.

Using the regular expressions

Using regular expressions we can match patterns in a string and can be used to ensure that the date string is in the correct format.

Here is an example of how to use regular expressions to validate a date string in the format of “YYYY-MM-DD”:

$dateString = '2023-03-26';
$datePattern = '/^\d{4}-\d{2}-\d{2}$/';

if (preg_match($datePattern, $dateString)) {
    echo "Valid date string format";
} else {
    echo "Invalid date string format";
}

Explanation

In the example above, we define the date string $dateString and the regular expression pattern $datePattern. We then use the preg_match() function to check if the date string matches the regular expression pattern.

If the date string matches the regular expression pattern, the preg_match() function will return true which means the date string is in the correct format else it returns false which indicates the date string is in invalid format.

Categorized in:

Tagged in: