Ruby-on-rails 验证 Rails 中的日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1325506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating date formats in rails
提问by cakeforcerberus
My simple date validation regex is not working correctly...
我的简单日期验证正则表达式无法正常工作...
validates_format_of :dob, :with => /\d{2}\/\d{2}\/\d{4}/, :message => "^Date must be in the following format: mm/dd/yyyy"
What am I missing here? I'm trying to validate that a date is in the following format: mm/dd/yyyy - When I enter what should be valid data, I still get the error message.
我在这里缺少什么?我正在尝试验证日期是否采用以下格式:mm/dd/yyyy - 当我输入什么应该是有效数据时,我仍然收到错误消息。
Thanks for the help so far. Here's a snippet of code from my form that is passing the dob value in:
感谢你目前的帮助。这是我的表单中的一段代码,它传递了 dob 值:
<tr>
<td>
<%= f.label :dob, "Date of Birth: " %>
</td>
<td>
<%= calendar_date_select_tag "user[dob]", "", :format => :american, :year_range => 50.years.ago..0.years.ago %>
</td>
</tr>
I think it may have something to do with my use of this js calendar plugin. A related problem is that my dob value is not maintained in the field if the post fails validation - the previously entered date value clears out...
我想这可能与我使用这个js日历插件有关。一个相关的问题是,如果帖子验证失败,我的 dob 值不会保留在字段中 - 之前输入的日期值会被清除......
Thanks!
谢谢!
Tom
汤姆
采纳答案by James Thompson
I've not tested your code within a Rails app, but your regular expression looks good to me. Try this test program:
我没有在 Rails 应用程序中测试过你的代码,但你的正则表达式对我来说看起来不错。试试这个测试程序:
#!/usr/bin/ruby
str = '08/24/2009'
regex = /\d{2}\/\d{2}\/\d{4}/
if str =~ regex
print 'matched', "\n"
else
print 'did not match', "\n"
end
Your regular expression matches. That suggests the problem is elsewhere.
您的正则表达式匹配。这表明问题出在其他地方。
You also might think about trying more general solutions for parsing a date in Ruby, such as the Date.parsemethodof the Dateclass. This does a little bit more validation than your regular expression, and it also provides some useful methods for converting dates between different formats.
你也不妨考虑一下解析在Ruby中,日期如想更通用的解决方案Date.parse方法的的Date类。这比您的正则表达式做更多的验证,并且它还提供了一些在不同格式之间转换日期的有用方法。
回答by Julik
You are probably using a string field to store a date. Consequently, any helpers that expect a DateTime or Time value will not work properly. You will need to investigate multiparameter assignments in Rails to figure out the proper way to do what you want to do (multiparemeter assignments is the magic behind sending 4 fields to Rails and get them converted to a DateTimeor Timeobject).
您可能正在使用字符串字段来存储日期。因此,任何需要 DateTime 或 Time 值的助手都将无法正常工作。您将需要研究 Rails 中的多参数分配,以找出做您想做的事情的正确方法(多参数分配是向 Rails 发送 4 个字段并将它们转换为 aDateTime或Time对象背后的魔法)。
In other words: if you are using a true DateTime field (as you should for this case) the validates_format_of will not have any effect (or will have adverse effects)
换句话说:如果您使用的是真正的 DateTime 字段(对于这种情况应该如此),则 validates_format_of 将不会产生任何影响(或会产生不利影响)
回答by Dom
Found an excellent gem / plugin for all your date / time validations.
为您的所有日期/时间验证找到了一个出色的 gem/插件。
validates_timeliness
validates_timeliness
回答by Matt Rogish
Ahhh! Forcing date formats on the end-user when Rails implicitly converts them is a bad thing for usability, along with being more work for you (as you've seen).
啊!当 Rails 隐式转换日期格式时,强制最终用户使用日期格式对可用性来说是一件坏事,同时也会为您带来更多工作(如您所见)。
If you've got a date/time attribute in your model, Rails will do its best to convert via Date.Parse (http://www.ruby-doc.org/core/classes/Date.html#M000644), e.g.
如果您的模型中有日期/时间属性,Rails 将尽最大努力通过 Date.Parse ( http://www.ruby-doc.org/core/classes/Date.html#M000644)进行转换,例如
u = Somemodel.find :first
u.created_at
=> Tue Nov 20 15:44:18 -0500 2007
u.created_at = '2008/07/03'
=> "2008/07/03"
u.created_at
=> Thu Jul 03 00:00:00 -0400 2008
u.created_at = '05/10/1980'
=> "05/10/1980"
u.created_at
=> Sat May 10 00:00:00 -0400 1980
回答by Jacob Mattison
The regex looks correct to me. A useful resource is http://www.rubyxp.com/, which will test your regular expression against a given string. Indeed, the regex you have matches a date I typed into rubyxp.
正则表达式对我来说是正确的。一个有用的资源是http://www.rubyxp.com/,它将针对给定的字符串测试您的正则表达式。实际上,您拥有的正则表达式与我在 rubyxp 中输入的日期相匹配。
Perhaps there's an issue in getting the entered data -- any chance the field is really called da?
也许在获取输入的数据时存在问题——这个字段真的有可能被称为 da 吗?
Another item you may find useful: validates_timeliness, a rails plugin to validate dates and times. Why just validate the date format when you can check if it's a real date -- after all, 99/99/9999 will validate against your regex, but you may not really want to accept that.
您可能会发现另一个有用的项目:validates_timeliness,一个用于验证日期和时间的 rails 插件。当您可以检查它是否是真实日期时,为什么只验证日期格式——毕竟,99/99/9999 将根据您的正则表达式进行验证,但您可能并不真的想接受这一点。
回答by geek123
You can try using current date to convert it into a format something like his:
您可以尝试使用当前日期将其转换为类似他的格式:
def validate_date_format(value)
current_date = DateTime.now
begin
DateTime.strptime(current_date, value)
rescue
raise 'Invalid Format'
end
end
回答by jonnii
You might also want to look into the Chronic Gem (http://chronic.rubyforge.org/) which does natural date parsing. So you can enter in :
您可能还想查看进行自然日期解析的 Chronic Gem ( http://chronic.rubyforge.org/)。所以你可以输入:
Next tuesday at 9pm
下周二晚上九点
And it will interpret it correctly.
它会正确解释它。

