LoginSignup
1
4

More than 1 year has passed since last update.

バリデーションをまとめる方法

Posted at

はじめに

アウトプット用に書かせて頂きます。

ユーザー管理機能を実装するためにuserテーブルにバリデーションをかけ、コードレビューをして頂いた回答で同じバリデーションをかけるときはまとめる事ができるという事を知りました。

with_options do

下記の記述でまとめる事ができます。

with_options do
#記述
end

ではまずwith_optionsを使わないコードを記述します。

user.rb
class User < ApplicationRecord

      validates :nickname, presence: true
      validates :birth_day, presence: true
      validates :first_name, presence: true 
      validates :last_name, presence: true
      validates :first_name_kana, presence: true
      validates :last_name_kana, presence: true
end

#presence trueとは空では登録できないようにするバリデーション

全てprecence: trueと同じバリデーションをかけているのでひとまとめにします。

user.rb
class User < ApplicationRecord

    with_options presence: true do
      validates :nickname
      validates :birth_day
      validates :first_name
      validates :last_name
      validates :first_name_kana
      validates :last_name_kana
    end
end

これでひとまとめにする事ができます。
しかしprecence true以外にもバリデーションをする時が多いと思います。

user.rb
class User < ApplicationRecord

      validates :nickname, presence: true 
      validates :birth_day, presence: true 
      validates :family_name, presence: true,
                             format: { with: /\A[ぁ-んァ-ヶ一-龥々]/ }
      validates :first_name presence: true,
                            format: { with: /\A[ぁ-んァ-ヶ一-龥々]/ }
      validates :family_name_kana, presence: true,
                                   format: {with: /\A[\p{katakana} ー-&&[^ -~。-゚]]+\z/ }
      validates :first_name_kana, presence: true, 
                                  format: {with: /\A[\p{katakana} ー-&&[^ -~。-゚]]+\z/ }

end

上記の記述で下記の正規表現を使いました。

正規表現 意味
/\A[ぁ-んァ-ヶ一-龥々]/ 全角ひらがな、全角カタカナ、漢字
/\A[\p{katakana} ー-&&[^ -~。-゚]]+\z/ 全角カタカナ    

このような時にwith_optionsの中にwith_optionsを入れ子のようにする事ができます。

user.rb
class User < ApplicationRecord

    #全行にpresence: trueをする
    with_options presence: true do
      validates :nickname
      validates :birth_day

      #この2行だけformat: { with: /\A[ぁ-んァ-ヶ一-龥々]/ }
      with_options format: { with: /\A[ぁ-んァ-ヶ一-龥々]/ } do
       validates :family_name 
       validates :first_name
      end
      #この2行だけ {with: /\A[\p{katakana} ー-&&[^ -~。-゚]]+\z/ }
      with_options format: {with: /\A[\p{katakana} ー-&&[^ -~。-゚]]+\z/ } do
       validates :family_name_kana
       validates :first_name_kana
      end
     end
end

以上です。
    

1
4
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
4