choise
choise

Reputation: 25244

validation in rails with two date attributes

so i have a model with two date attributes

  # migration
  t.date :valid_from
  t.date :valid_until

these are optional and you should be able to define only valid_from or valid_until, but if both dates are filled i want (of course) that valid_from is earlier than valid_until.

the best place to check for this, is inside the model with a validator, isnt it? i think the controller would not be the best place for this.

how could this be done with a validator inside my model? i tried several things without luck.

Upvotes: 4

Views: 1561

Answers (2)

Robin
Robin

Reputation: 21884

If you find yourself having to validates a lot of dates, you might want to add the date validator gem! It gives you a nice syntax and probably all the flexibility you need.

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124419

You could use a custom validator:

validate :valid_date_range_required

def valid_date_range_required
  if (valid_from && valid_until) && (valid_until < valid_from)
    errors.add(:valid_until, "must be later than valid_from")
  end
end

Upvotes: 5

Related Questions