Home >Backend Development >PHP Tutorial >PHP Date Validation: Can\'t the Regular Expression Match?
PHP Date Validation: Troubleshooting a Regular Expression
You're attempting to validate dates in PHP using a regular expression, but you're encountering issues. Let's analyze your code and offer a more robust solution.
The regular expression you provided, %A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)ddz%, appears to be correct for validating MM/DD/YYYY format. However, the code you're using to match the date is incorrect. You're assigning the result of preg_match to $_POST['birthday'], which is not what you intended.
Improved Validation Using checkdate
Instead of using a regular expression, you can simplify the validation process by leveraging PHP's checkdate function. This function takes month, day, and year as separate parameters and returns a Boolean value indicating whether the date is valid or not.
<code class="php">$test_date = '03/22/2010'; $test_arr = explode('/', $test_date); if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) { // valid date ... }</code>
In this code, we convert the /-separated date string into an array of month, day, and year components. Then, we pass these components to checkdate to verify the validity of the date.
Additional Layer of Input Validation
For enhanced input validation, consider the following code:
<code class="php">$test_date = '03/22/2010'; $test_arr = explode('/', $test_date); if (count($test_arr) == 3) { if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) { // valid date ... } else { // problem with dates ... } } else { // problem with input ... }</code>
This approach first checks if the input string contains exactly three components (month, day, year) by counting the elements in $test_arr. If the count is different from 3, it suggests a potential error in the input. Subsequently, it validates the date using checkdate.
The above is the detailed content of PHP Date Validation: Can\'t the Regular Expression Match?. For more information, please follow other related articles on the PHP Chinese website!