简体   繁体   English

在rails中验证日期格式

[英]Validating date formats in rails

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. 我认为这可能与我使用这个js日历插件有关。 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... 一个相关的问题是,如果帖子验证失败,我的dob值不会在字段中维护 - 先前输入的日期值清除...

Thanks! 谢谢!

Tom 汤姆

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. 因此,任何期望DateTime或Time值的帮助程序都将无法正常工作。 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 DateTime or Time object). 您将需要研究Rails中的多参数分配,以找出执行您想要做的事情的正确方法(多参数分配是将4个字段发送到Rails并将它们转换为DateTimeTime对象的魔力)。

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将不会产生任何影响(或会产生不利影响)

Found an excellent gem / plugin for all your date / time validations. 为您的所有日期/时间验证找到了一个出色的宝石/插件。

validates_timeliness validates_timeliness

http://github.com/adzap/validates_timeliness http://github.com/adzap/validates_timeliness

I've not tested your code within a Rails app, but your regular expression looks good to me. 我没有在Rails应用程序中测试你的代码,但你的正则表达式对我来说很好。 Try this test program: 试试这个测试程序:

#!/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.parse method of the Date class. 您也可以考虑尝试使用更通用的解决方案来解析Ruby中的日期,例如Date类的Date.parse方法 This does a little bit more validation than your regular expression, and it also provides some useful methods for converting dates between different formats. 这比正则表达式更有效,它还提供了一些在不同格式之间转换日期的有用方法。

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 ), eg 如果您的模型中有日期/时间属性,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

The regex looks correct to me. 正则表达式对我来说是正确的。 A useful resource is http://www.rubyxp.com/ , which will test your regular expression against a given string. 一个有用的资源是http://www.rubyxp.com/ ,它将针对给定的字符串测试您的正则表达式。 Indeed, the regex you have matches a date I typed into rubyxp. 实际上,你所使用的正则表达式与我输入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. 您可能觉得有用的另一个项目: validates_timeliness ,一个用于验证日期和时间的rails插件。 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. 为什么只有在你可以检查它是否真实日期时验证日期格式 - 毕竟99/99/9999将验证你的正则表达式,但你可能不想接受它。

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

You might also want to look into the Chronic Gem ( http://chronic.rubyforge.org/ ) which does natural date parsing. 您可能还想查看使用自然日期解析的Chronic Gem( http://chronic.rubyforge.org/ )。 So you can enter in : 所以你可以输入:

Next tuesday at 9pm 下周二晚上9点

And it will interpret it correctly. 它会正确地解释它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM