4

I'm trying to validate dates like DD/MM/YYYY with PHP using preg_match(). This is what my REGEX expression looks like:

$pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";

But using it with a correct value, I get this message:

preg_match(): Unknown modifier '('

Complete code:

    $pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";
    $date = "01/03/2011";

    if(preg_match($pattern, $date)) return TRUE;

Thank you in advance

Pradeep
  • 9,667
  • 13
  • 27
  • 34
udexter
  • 2,307
  • 10
  • 41
  • 58

5 Answers5

13

Escape the / characters inside the expression as \/.

$pattern = "/^([123]0|[012][1-9]|31)\/(0[1-9]|1[012])\/(19[0-9]{2}|2[0-9]{3})$/";

As other answers have noted, it looks better to use another delimiter that isn't used in the expression, such as ~ to avoid the 'leaning toothpicks' effect that makes it harder to read.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
3

You use / as delimiter and also in your expression. Now

/^([123]0|[012][1-9]|31)/

Is the "complete" expression and all following is expected as modifier, also the (.

You can simply use another delimiter.

~^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$~

Or you escape all occurence of / within the expression, but I would prefer another delimiter ;) Its more readable.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
2

your delimiter is /, but you are using it inside the pattern itself. Use a different delimiter, or escape the /

NoBBy
  • 497
  • 4
  • 15
1

You could escape the slashes / as suggested. It'll eventually lead to the Leaning Toothpick Syndome, though.

It's common to use different delimiters to keep your regular expression clean:

// Using "=" as delimiter
preg_match('=^ ... / ... $=', $input);
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
0

checek date using below function

 function checkDateFormat($date)
    {
      //match the format of the date
      if (preg_match ("/^([0-9]{2}) \/([0-9]{2})\/([0-9]{4})$/", $date, $parts))
      {
        //check weather the date is valid of not
        if(checkdate($parts[2],$parts[1],$parts[3]))
          return true;
        else
         return false;
      }
      else
        return false;
    }

echo checkDateFormat("29/02/2008"); //return true
echo checkDateFormat("29/02/2007"); //return false
xkeshav
  • 53,360
  • 44
  • 177
  • 245