Mazterkizh
Mazterkizh

Reputation: 11

Rails: How to add Validations for wrong dates eg November 31 and June 31. Ihave used :date as my column type

I have a form that looks like this views/profiles/_form

<div class="field2">
<%= f.label :purchase_date, "Date this horse was purchased" %><br />
<%= f.date_select :purchase_date %>
</div>

<div class="field2">
<%= f.label :owner_name, "Owner Name" %><br />
<%= f.text_field :owner_name %>
 </div>

what validation do i add in my model/profile.rb

validates :purchase_date ????????

Upvotes: 0

Views: 53

Answers (2)

MrDanA
MrDanA

Reputation: 11647

You want the exclusion validation. It looks like this:

# Made it a constant, but could also be in a method.
EXCLUSION_DATE = [Date.new(2012,1,1), Date.new(2012,2,1)]
validates :purchase_date, :exclusion => { :in => EXCLUSION_DATES }

You can also always add your own custom validations:

validate :check_purchase_date # Name it whatever you want

private
  def check_purchase_date
    exclusion_dates = [Date.new(2012,1,1), Date.new(2012,2,1)]
    if exclusion_dates.include?(self.purchase_date)
      self.errors.add(:purchase_date, "cannot be on a reserved date.")
    end
  end

Upvotes: 1

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

why not let the user select from jquery datepicker for example, so that you can eliminate tje problem straightaway?

Upvotes: 0

Related Questions