ExiRe
ExiRe

Reputation: 4767

Rails 3.2 - validate format of date

I have the model Teacher which has field :teacher_birthday. I get :teacher_birthday from the view (a single textbox). I want to make sure that an input date has a such format - dd.mm.yyyy (i mean i want to be sure, that an input date as 12.24.1991 will not be save in db because such date is wrong) and that this date exists. Also, i want to do this in the MODEL. Is this possible?

Upvotes: 0

Views: 1174

Answers (2)

Mori
Mori

Reputation: 27799

Try the chronic gem. It has very flexible date parsing, including what you're looking for:

[11] pry(main)> require 'chronic'
=> true
[12] pry(main)> Chronic.parse('24.12.1991'.gsub('.','-'))
=> 1991-12-24 12:00:00 -0700

Upvotes: 1

Nikhil
Nikhil

Reputation: 3152

Declare the validation method to be called in your model, and then define this method. The following should roughly do what you need:

validate :validate_teacher_birthday

private

def validate_teacher_birthday
  errors.add("Teacher birthday", "is invalid.") unless (check_valid_date && valid_date_format)
end

def valid_date_format
  self.teacher_birthday.match(/[0-9][0-9].[0-9][0-9].[0-9][0-9][0-9][0-9]/)
end

def check_valid_date
  begin
    parts = self.teacher_birthday.split(".") #contains array of the form [day,month,year]
    Date.civil(parts[2].to_i,parts[1].to_i,parts[0].to_i)
  rescue ArgumentError
    #ArgumentError is thrown by the Date.civil method if the date is invalid
    false
  end
end

Upvotes: 0

Related Questions