0

I am trying to check the date field is in format 'd/m/yyyy/ and /dd/mm/yyyy.. Can anyone provide me idea to do so...

US-1234
  • 1,519
  • 4
  • 24
  • 61
  • 5
    Don't use a regex. Use DateTime class instead. See [this answer](http://stackoverflow.com/a/19271434/1438393). – Amal Murali Mar 15 '14 at 12:10
  • 1
    Can get quite elaborate for days in a month... 28, 30, or 31 days, do we take leap years into account? – Wrikken Mar 15 '14 at 12:16

2 Answers2

1

Apart from wether or not you should or should not use regex, this is the way:

\d{1,2}/\d{1,2}/\d{4}
  • \d means digits ( [0-9] )
  • {1,2} means 'the part before me should have at least 1 length, and maximum 2
  • {4} means exactly 4 characters long

Edit: This will match 1/2/2014 (both single), 11/12/2014 (both double) and 1/12/2014 (a single and a double).

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Martijn
  • 15,791
  • 4
  • 36
  • 68
  • I am getting this error, preg_match(): "Delimiter must not be alphanumeric or backslash" – US-1234 Mar 15 '14 at 12:24
  • 1
    @Manadh: It seems you're using the regex as-is. You need to wrap it within valid delimiters: `/\d{1,2}/\d{1,2}/\d{4}/`. – Amal Murali Mar 15 '14 at 12:26
  • Which you could've found yourself with that exact query in google :) – Martijn Mar 15 '14 at 12:31
  • I tried it in google but i am getting this error :preg_match(): Unknown modifier '/' – US-1234 Mar 15 '14 at 12:33
  • Use a delimiter to go around the regular expression above. For example, I am using the tilde `~` as a delimiter here. `if (preg_match('~\d{1,2}/\d{1,2}/\d{4}~', $date)) { print "DATE MATCHES"; }` – Quixrick Mar 15 '14 at 15:37
  • I presonally prefer the slash `/`, because in other programming languages that is common. That would require to escape the slashes in the regex to make them as content, not the end delimiter (so every `/` becomes `\/`) – Martijn Mar 15 '14 at 16:20
0

Try this

$yourdate="1/12/2002";
if (preg_match("/\d{1,2}\/\d{1,2}\/\d{4}/", $yourdate)) {
echo "Valid Date";
} else {
echo "Invalid Date";
}
Shafeeq
  • 467
  • 7
  • 17