I think this can do what you need:
class User < ActiveRecord::Base def dob_string @dob_string || (dob ? dob.strftime("%m/%d/%Y") : "") end def dob_string=(dob_s) unless convert_preferred_date(dob_s) || convert_acceptable_date(dob_s) errors.add(:dob, 'The birth date is not in the correct format (MM/DD/YYYY)') @dob_string = dob_s end end private def convert_preferred_date(dob_s) convert_date(dob_s, "%m/%d/%Y") end def convert_acceptable_date(dob_s) convert_date(dob_s, "%m-%d-%Y") end def convert_date(dob_s, format) self.dob = (dob_s && !dob_s.empty? ? Date.strptime(dob_s, format) : nil) rescue ArgumentError nil end end
This is a little inelegant, but I can't think of a way to make only two date formats. If you are ready to accept any format of human readable data, there is a much simpler way to do this.
Test this in your application. I just messed around with this in the Rails console, and I may not have tested every case. Hope this helps.
source share