LoginSignup
1
0

More than 1 year has passed since last update.

[Rails]date_validatorで日付に関するバリデーションを。

Posted at

date_validatorとは

簡単に日付(date)に関するバリデーションを設定出来るgemのことです。

使い方

基本形

validates :expiration_date, date: true

範囲を指定したい場合

afterには指定した日付より後のみ許可し、beforeには指定した日付より前のみ許可します。

  validates :birthday, date: {
    # 1900年1月1日より後で現在の日付までの範囲のみ許可する
    after: Date.new(1900, 1, 1),
    before: ->(obj) { Date.today }
  }

after_or_equal_toだと、指定した日付以降のみ許可し、before_or_equal_toでは指定した日付以前のみ許可します。

validates :due_date,  date: {
  # 1900年1月1日以降で現在の日付以前の範囲のみ許可する
  after_or_equal_to: Date.new(1900, 1, 1),
  before_or_equal_to: ->(obj) { Date.today }
}

参考

date_validator

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0