10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「年が空だと月は入れたらだめ」みたいな時の validation

Posted at

year が空かどうかで month の条件を切り替えているのがポイントです。

ついでに year が未来の年でないかもチェックしています。

validates :year,
          numericality: {
            only_integer: true,
            greater_than_or_equal_to: 1900,
            less_than_or_equal_to: ->(_model) { Date.today.year }
          },
          allow_nil: true
validates :month,
          numericality: {
            only_integer: true,
            greater_than_or_equal_to: 1,
            less_than_or_equal_to: 12
          },
          allow_nil: true,
          unless: ->(model) { model.year.nil? }
validates :month,
          absence: true,
          if: ->(model) { model.year.nil? }
10
10
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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?