2

What's wrong with this?

public static function validaDataHoraBR($data_hora){
  $pattern = "/^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/\d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$/";
  return (preg_match($pattern, $data_hora)) ? array(true) : array(false,' não é uma data e hora no formato BR!<br>'); 
}

This pattern validate this - 20/08/2011 21:00:00

Error: Message: preg_match() [function.preg-match]: Unknown modifier '('

pedrosalpr
  • 155
  • 1
  • 9
  • 3
    Why are you using a Regex to validate a date? [Use `DateTime` class instead](http://stackoverflow.com/a/19271434/1438393). – Amal Murali Nov 01 '13 at 12:20

1 Answers1

5

Escape / in the regular expression.

"/^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])\/([1-9]|1[0,1,2])\/\d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$/"
#                                   ^                 ^

Otherwise, / is recognised as end of the regular expression.

Or use different delimiters:

"#^([1-9]|0[1-9]|[1,2][0-9]|3[0,1])/([1-9]|1[0,1,2])/\d{4} ([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}(:([0-5][0-9])){1,2}$#"
falsetru
  • 357,413
  • 63
  • 732
  • 636