M
M
Megapiharb2016-10-31 01:03:14
Ruby on Rails
Megapiharb, 2016-10-31 01:03:14

How to validate valid dates?

There is this form:

<div class="form-group">
      <%= f.label :date_of_birth %>
      <p><%= f.date_select :date_of_birth, start_year: Date.today.year - 111, end_year: Date.today.year, class: 'form-control' %></p>
    </div>

in bd date_select-t.datetime :date_of_birth

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Grudinkin, 2016-10-31
@Hunt666

stackoverflow.com/questions/11736786/rails-3-custo...
something like this in the relevant model:

validate :model_condition


def model_condition
    if self.date_of_birth < (Date.today.year - 111.year)
      errors.add(:date_of_birth, "some error")
    end
  end

M
Megapiharb, 2016-10-31
@Megapiharb

Thank you. I understood the idea.
I just had to change it like this:

validate :model_condition

  def model_condition

    count = DateTime.now.year - 111
    date_1905 = DateTime.new(count) # экземпляр даты за за прошедшие 111

    # если дата не в назначеном диапазоне, выбивает ошибку и валидация не проходит
    unless self.date_of_birth.between?(date_1905, DateTime.now)
      errors.add(:date_of_birth, "some error")
    end
  end

Now it works as it should :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question