LoginSignup
1
0

More than 1 year has passed since last update.

よく使うバリデーション (#コピペメモシリーズ)

Last updated at Posted at 2021-08-03

バリデーションとは

不正なデータがデータベースに保存されないようにデータをチェックするシステムをバリデーションという。
不正なデータの場合はデータベースに保存されない。

validates 書き方

モデルクラスにvalidatesメソッドを指定することで、バリデーションをかけることができる。(バリデーションはモデルで設定する。)
このときに、validatesを用いてカラム名と内容を指定する。

バリデーションの種類 一部分

# ・validates :カラム名, バリデーションしたい条件: 内容
# ・最大文字数:length: { maximum: 20 }
# ・最小文字数:length: { minimum: 20 }
# ・文字数の範囲:length: { in: 1..30 }
# ・空でない:presence: true
# ・他と被っていない:uniqueness: true
# ・正規表現:format: { with: /<正規表現>/}
# ・「<属性名>_confirmation」と一致:confirmation: true
例)
validates :name,  presence: true, length: { in: 2..20 }, uniqueness: true
validates :introduction, length: { maximum: 50 }

この場合
nameに空でない且つ2〜20文字の範囲で他と被っていないバリデーション
introductionに最大文字数50文字までのバリデーションがかかっています。

自分はよくバリデーションの書き方を忘れるのでmodelファイルに

# ・最大文字数:length: { maximum: 20 }
# ・最小文字数:length: { minimum: 20 }
# ・文字数の範囲:length: { in: 1..30 }
# ・空でない:presence: true
# ・他と被っていない:uniqueness: true
# ・正規表現:format: { with: /<正規表現>/}
# ・「<属性名>_confirmation」と一致:confirmation: true

バリデーションの書き方を貼り付けて作業しています。

終わり

1
0
2

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