使用正则表达式验证日期格式 [英] Validating date format using regular expression

查看:49
本文介绍了使用正则表达式验证日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用正则表达式,我将如何验证日期以确保它仅以这种格式输入:mm/dd/yyyy?

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

如果有人感兴趣,我正在使用 validates_format_of :date_field, :with =>// 在 Ruby 模型中.

If anyone is interested, I'm using validates_format_of :date_field, :with => // in a Ruby model.

推荐答案

@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}$/

正如@Tim 所说,这不是 100% 正则表达式验证器.请参阅他的链接答案.

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

编辑 #2:上面的 Ruby 特定版本.

Edit #2 : Ruby specific version above.

这篇关于使用正则表达式验证日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆