Regular Expression Help for Date Validation - dd/mm/yyyy - PHP
Solution 1
I think you should escape the slashes /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/
Solution 2
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 differentiate between dates and months, but also validate only 2 centuries.
Solution 3
You need to escape the slash since you are using it as regex delimiter
/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/
or use different regex delimiters
#^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$#
Solution 4
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] );
}
michaelmcgurk
BY DAY: Alt-Rock Ninja Cowgirl at Veridian Dynamics. BY NIGHT: I write code and code rights for penalcoders.example.org, an awesome non-profit that will totally take your money at that link. My kids are cuter than yours. FOR FUN: C+ Jokes, Segway Roller Derby, NYT Sat. Crosswords (in Sharpie!), Ostrich Grooming. "If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers
Updated on July 27, 2022Comments
-
michaelmcgurk almost 2 years
Can someone show me the error of my ways when it comes to this regular expression:
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$/", $_POST["date"]) === 0) { echo 'error'; }
Basically I want this to display an error message each time - unless the format is correct (dd/mm/yyyy).
What am I doing wrong with the above?
Many thanks for any pointers.
-- updated regex above shortly after posting - apologies for inconvenience --
-
michaelmcgurk about 12 yearsFantastic. That now works perfectly. Silly me :)
-
michaelmcgurk about 12 yearsMany thanks for this. I will green tick shortly :)
-
happy_marmoset over 7 yearsAnd if you need to capture
^([0-2]\d|3[0-1])\/(0\d|1[0-2])\/((?:19|20)\d{2})$
and also have added begining and ending anchors. Also there is a bug that dates with zero day and month will work '00/00/1999'. -
Kirk Patrick Brown over 6 yearsthank you. this work for me also. Voted you up.