LoginSignup
2
2

More than 5 years have passed since last update.

date_selectにバリデーションかける

Last updated at Posted at 2017-04-12

f.date_selectで過去の日付は弾き方。

Gemfile
gem 'jc-validates_timeliness'
$ bundle install

必要なファイル群をインストール

bundle exec rails g validates_timeliness:install

エラーメッセージを日本語表示するためにファイルをコピー。

cp config/locales/validates_timeliness.en.yml config/locales/validates_timeliness.ja.yml
validates_timeliness.ja.yml
ja:
  errors:
    messages:
      invalid_date: "は正しい形式で入力してください。"
      invalid_time: "は正しい形式で入力してください。"
      invalid_datetime: "は正しい形式で入力してください。"
      is_at: " %{restriction} である必要があります。"
      before: " %{restriction} より前を指定してください。"
      on_or_before: " %{restriction} 以前を指定してください。"
      after: " %{restriction} より後を指定してください。"
      on_or_after: " %{restriction} 以降を指定してください。"
  validates_timeliness:
    error_value_formats:
      date: '%Y-%m-%d'
      time: '%H:%M'
      datetime: '%Y-%m-%d'

日付だけ表示されればよかったので、時間と秒は削除しました。

ja.ymlを持っていない場合はインストール

wget -O config/locales/ja.yml https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml

あとはmodelにバリデーションを書くだけ。
今回は昨日以前の日付を弾きたかったので、on_or_after: Date.todayを追記
model_name.rb
validates :column_name, timeliness: { on_or_after: Date.today }

以上です。

2
2
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
2
2