Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating date format using regular expression

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_format_of :date_field, :with => // in a Ruby model.

like image 640
Artem Kalinchuk Avatar asked Aug 08 '26 13:08

Artem Kalinchuk


2 Answers

Regex for this format can looks like:

^\d{2}\/\d{2}\/\d{4}$
like image 108
hsz Avatar answered Aug 10 '26 09:08

hsz


@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.

like image 24
FailedDev Avatar answered Aug 10 '26 07:08

FailedDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!