This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
How do we assure that the date is in the correct format and is actually a valid date? In this video, we'll explore one option for validating string formats and checking for a valid date.
Documentation
explode() Split a string by string
strlen() Get string length
checkdate() Validate a Gregorian date
Regular Expressions
Another option you often see for validating strings, is the use of regular expressions. A regular expression (regex or regexp for short) is a special text string for describing a search pattern. Regular expressions are a great tool to learn. Most applications as well as most programming languages include some form of regular expression matching.
PHP includes a number of Regular Expression Functions. We could use preg_match to match our dates as well.
Example:
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $date, $dateMatch)) {
if (!checkdate($dateMatch[1], $dateMatch[2], $dateMatch[3])) {
$error_message = 'Invalid Date';
}
} else {
$error_message = 'Invalid Date format';
}
This matches a string that starts with (^) 2 digits (\d{2}), followed by a forward slash (\/), then another 2 digits (\d{2}) followed by another forward slash (\/), and finally 4 digits (\d{4}) at the end($).
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up