开发者

Php regex date validation

开发者 https://www.devze.com 2023-02-11 06:52 出处:网络
I\'m trying to validate a date input by the use of regex. if(!preg_match(\"/^[0-9]{4}\\/[0-9]{2}\\/[0-9]{2}$/\", $_POST[\'variant\'][\'sales_start\'])) {

I'm trying to validate a date input by the use of regex.

if(!preg_match("/^[0-9]{4}\/[0-9]{2}\/[0-9]{2}$/", $_POST['variant']['sales_start'])) { 
  echo "invalid";
}

The string I'm trying to input is 2011-02-03, however it's failing, and I can't seem to figure out why.

Can someone please tell me what I'm doing wrong?

Thanks in 开发者_StackOverflowadvance


You're separating the date with dashes and the regex is looking for slashes?

Try

if ( !preg_match( "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $_POST['variant']['sales_start'] ) )
{ 
    echo "invalid";
}


You haven't allowed for other separators besides /, but I also notice your regex will allow things like 9999/99/99. Try something like this:

"/^(?:20|19)[0-9]{2}([-.\\/])(?:0?[1-9]|1[012])\\1(?:0?[1-9]|[12][0-9]|3[01])$/"

It's not perfect, but it's pretty close. This will allow any of the following:

  • 1999/10/29
  • 2011-1-13
  • 2013.06.05

It will disallow the following:

  • 1999/10.29
  • 2011-6/20
  • 9090-76-56
  • 0000.00.00

Double-check the [-.\\/] part; I'm not used to PHP these days, so I'm not sure whether you need the \\.


Also, use PHP function checkdate() in order to validate your date according to Gregorian calendar - http://php.net/manual/en/function.checkdate.php


Building from Justin's answer I wanted to add filtering for text formatted dates as well.

Allows:

  • March 13, 2014
  • Oct. 11, 1940
  • July 1910
  • 10 September 2000
  • 01/17/2010
  • 20/11/1999

etc.

"#^(((?:0?[1-9]|1[012])|(?:0?[1-9]|[12][0-9]|3[01])|([a-zA-Z]+))([.,]?[-.\\\/\s]))?(((?:0?[1-9]|1[012])|(?:0?[1-9]|[12][0-9]|3[01])|([a-zA-Z]+))([.,]?[-.\\\/\s]))?((?:20|19)[0-9]{2})$#"

I have limited the years to 19XX and 20XX in this solution, but you can modify that if needed. I'm also not allowing the year in the first position because it's not a typical user format.

Also, if you plan to use this with JS be sure to remove the extra '\' escape in the two separated segments. (I found that PHP required '/' to be escaped where JS did not)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号