Change format for date input in Rails 3?
I am using a text_field
for date input in Rails 3 and would like the date to be formatted as mm/dd/yyyy
.
While I've found a few solutions for displaying the date in that way, I haven't run across a workable method for accepting that format as an input.
The problem is that in the case of ambiguous dates like 开发者_如何学运维"09/05/2011"
, Rails interprets it as "May 9th" rather than "September 5th."
What is the best way to get Rails 3 to interpret those sorts of inputs according to the mm/dd/yyyy
format?
Hopefully your target audience is solely American, since that date format is not used many places outside the US.
Anyway, you just want to validate the format of the string:
validates_format_of :the_date, :with => /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/
That's a very rudimentary pattern that validates the format of the string, but not the actual values between the separators. If you want to do that, your best bet is probably just to try parsing the date with Date#strptime
and see if it parses or not.
I ran into an issue where users were filling out a text field with month/day/year. But due to the new Date parsing, Rails admitted they entered day/month/year. I solved it by patching Date._parse in Rails. Therefore I added a date_patch.rb in the initializers folder.
require 'time'
class Date
class << self
alias :org_parse :_parse
# switch the month and day field for expecting US dates
def _parse(str, comp=true)
str = str.sub(/(\d{1,2})\/(\d{1,2})\/(\d{1,4})/, '\2/\1/\3')
org_parse str, comp
end
end
end
精彩评论