PHP Date Validation: Can\'t the Regular Expression Match?

DDD
Release: 2024-10-23 06:08:30
Original
239 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!