Friday, February 24, 2012

Re: [Rails] Re: How to validate a submited date with select boxes?

On 25.02.2012, at 0:57, Bob Smith wrote:

>
> I also used strings, as it is much easier to enter a date with text
> than picking each field from the dropdowns. I made it so that if you
> enter a full year, fine. But if you do a 1 or 2 digit year it will
> pick the rest of the year correctly. If you have 130 year old dates
> you will have to enter all 4 digits.

I prefer to pick up the date from ONE string:

model:

class Software << ActiveRecord::Base

formatted_date_accessor :release_date

end


lib: (/lib/formatted_date_time.rb)

class ActiveRecord::Base

def self.formatted_date_accessor(*names)
names.each do |name|
define_method("#{name}=") do |value|
super(value)
if value.present? && self[name].nil?
class_eval do
define_method name.to_sym do
value
end
end
self.class.validate do
errors.add(name.to_sym, "can't be formatted")
end
end
end
end
end

end


in a View:

<%= f.text_field :release_date %>


You can pass Jan 2, 2011 as:
'2011-1-2' or 11-1-2 or 2011.1.2 or 11.01.02, according to a Date's localization order.
European order would be: '02.01.2011' or '2-1-2011' whatever...

Any invalid date will raise a validation error. Any posted date saved for the next request to trace the invalid input.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate