[Ruby] [Validation] rails How to specify after today’s date

less than 1 minute read

【goal】

When entering a date, you can only enter dates after today
Validate

【merit】

■ Improvement of UX
■ Improved understanding of validate

【Development environment】

■ Mac OS catalina
■ Ruby on Rails (5.2.4.2)
■ Virtual Box:6.1
■ Vagrant: 2.2.7

【Implementation】

  • Create validate with any method name
  • Added method processing
    ① Judge whether it is empty by “return if start_day.blank?”
    ② Get today’s date with “if start_day <Date.today” & conditional branch & comparison
    ③ Define the error statement in “errors.add”
     

model/item.rb





validate :date_before_start
validate :date_before_finish



  def date_before_start
    return if start_day.blank?
    errors.add(:start_day, "Please select the one after today") if start_day < Date.today
  end

  def date_before_finish
    return if finish_day.blank? || start_day.blank?
    errors.add(:finish_day, "Please select the one after the start date") if finish_day < start_day
  end

that’s all! !!

[I want to read it together]

■ Differences between Time, Date, DateTime, TimeWithZone between Ruby and Rails
https://qiita.com/jnchito/items/cae89ee43c30f5d6fa2c

■ [ERROR message display] A simplified version that can be used at any time with the rails partial template.
https://qiita.com/tanaka-yu3/items/63b189d3f15653cae263

■ [Date.today] How to retrieve information only for today rails
https://qiita.com/tanaka-yu3/items/741711bd743b80eda51a