Validating date format using regular expression

后端 未结 2 1892
情书的邮戳
情书的邮戳 2021-01-20 14:09

Using regular expression, how would I validate a date to make sure it is only entered in this format: mm/dd/yyyy?

If anyone is interested, I\'m using validates

2条回答
  •  耶瑟儿~
    2021-01-20 14:47

    @hsz answer is correct. Should you need to also validate the date itself you can use this :

    /^(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[1-2]\d|3[01])/\d{4}$/
    

    Edit :

    As @Tim said this will is not a 100% regex validator. See his linked answer for that.

    if subject =~ /\A(?:0?[1-9]|1[0-2])\/(?:0?[1-9]|[1-2]\d|3[01])\/\d{4}\Z/
        # Successful match
    

    Edit #2 : Ruby specific version above.

提交回复
热议问题