[ACCEPTED]-Regular Expression Help for Date Validation - dd/mm/yyyy - PHP-preg-match

Accepted answer
Score: 18

I think you should escape the slashes /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

0

Score: 4

You need to escape the slash since you are 2 using it as regex delimiter

/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/

or use different 1 regex delimiters

#^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$#
Score: 4

You can also use this one:

([0-2]\d|3[0-1])\/(0\d|1[0-2])\/(19|20)\d{2}

if you want to 2 differentiate between dates and months, but 1 also validate only 2 centuries.

Score: 2

I use this for checking dates

private function validate_date( $date, $empty_allowed = true ) {

    if ( empty( $date ) ) {
        return $empty_allowed;
    }

    if ( ! strpos( $date, '/' ) ) {
        return false;
    }

    if ( substr_count( $date, '/' ) !== 2 ) {
        return false;
    }

    if ( preg_match( '/(0[1-9]|1[0-9]|3[01])\/(0[1-9]|1[012])\/(2[0-9][0-9][0-9]|1[6-9][0-9][0-9])/', $date ) !== 1 ) {
        return false;
    }

    $split = explode( '/', $date );

    return checkdate( $split[1], $split[0], $split[2] );

}

0

Score: 0

This is the easiest way to solve your problem.

^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$

Output 1 looks Like=> 31/12/2019

Test Demo

More Related questions