RAILS: date_select validation

1.4k views Asked by At

custom_form.html.erb

<%= f.date_select :creation_date %>

I have a column creation_date in my database with date type. Everything works fine, but I need to validate :creation_date in my server.rb model.
I need to validate:

  1. Date type to be valid
  2. Max\min date start\end period

Simple :creation_date validation validates_date :creation_date, presence =>true ... calling Undefined Method error.
I read on a forum that if date is not valid, then my :creation_date will be set to nil.

I guess we can check :creation_date for nil value to deal with 1 item in the list?

And how can I implement second item?

UPD (Resolved):

Problem was in neasted model. I tried to validate attribute of my user model in server.rb. I moved validation to user.rb and now i'm able to validate :creation_date with timeliness gem

3

There are 3 answers

0
Abdul Baig On

Try this:

class MyModel < ActiveRecord::Base
  validate :mydate_is_date

  private

  def mydate_is_date
    unless :mydate.is_a?(Date)
      errors.add(:mydate, 'must be a valid date') 
    end
  end
end
0
Sasi On

validates :creation_date, presence: true

This method is from default rails validation which checks for blank values or invalid dates if it is a date field.

0
ConnorCMcKee On

Regarding your first item, you've been given a number of totally acceptable answers (I would implement G.B.'s, personally).

Regarding your second item, it depends a little bit upon what your bounds are. In my opinion, the easiest way is to simply compare date objects. For instance:

validate :mydate_is_within_range

private

def mydate_is_within_range
  unless mydate > min_date && mydate < max_date
    errors.add(:mydate, 'date must be within the allowed range')
  end
end

Now, this relies on having the minimum and maximum dates in date form, but I suspect you already have this? Regardless, it should set you on the right track.