Php regex date validation

后端 未结 4 995
天命终不由人
天命终不由人 2020-12-12 01:03

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\'])) { 
           


        
4条回答
  •  孤城傲影
    2020-12-12 01:56

    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)

提交回复
热议问题