Railsのバリデーションの種類と使い方
プログラミングの勉強日記
2020年8月1日 Progate Lv.226
バリデーションとは
不正なデータがデータベースに保存されないようにデータをチェックするシステムをバリデーションという。バリデーションに引っかかった場合(不正なデータの場合)にはデータベースに保存されない。
基本的な書き方
モデルクラスにvalidates
メソッドを指定することで、バリデーションをかけることができる。(バリデーションはモデルで設定する。)このときに、validatesを用いてカルム名と内容を指定する。
validates :カラム名(シンボルで指定),検証ルール(こちらもシンボルで指定)
バリデーションの種類
空ではい(空のデータを登録できないようにする)
{presence: true}を用いることでそのカラムの値が存在するかどうかをチェックできる。
class Post < ApplicationRecord
validates :content, {presence: true}
end
boolean属性が空でないこと
class User < ApplicationRecord
validates :birthplace, inclusion: { in: [true, false] }
end
チェックボックス
class User < ApplicationRecord
validates :gender, {acceptance: true}
end
文字数の指定
length
を用いて{maximum:数値}
を指定することで最大文字数を{minimum:数値}
で最小文字列を指定することができる。またin
を使うことで範囲やその文字数のみのバリデーションをかけることもできる。
class Post < ApplicationRecord
# 最大140文字(140文字以下)
validates :content, {length : {maximum:140} }
# 50文字以上
validates :content, {length : {minimum:50} }
# 1文字以上75文字以下
validates :content, {length: {in: 1..75} }
# 5文字のみ
validates :content, {length: {is: 5} }
end
数値の指定
数値のみの入力を許可するときには、numericality
を使う。
class Actor < ApplicationRecord
validates :height, {numericality: true}
end
numericality
は様々なオプションがあるので、これらを用いることでより詳細なバリデーションをかけることができる。
オプション | 概要 |
---|---|
only_integer | integerのみ |
equal_to | 指定された値と等しいか |
greater_than_or_equal_to | 指定された値以上 |
less_than_or_equal_to | 指定された値以下 |
greater_than | 指定された値よりも大きいか |
less_than | 指定された値よりも小さいか |
odd | trueに設定した場合、奇数か |
even | trueに設定した場合、偶数か |
class Actor < ApplicationRecord
# 50より大きく250より小さい
validates :height, numericality: {greater_than: 50,less_than: 250}
end
任意で指定した値が含まれているかどうか
指定した値が含まれているか確認するときはinclusion
を使う。
class Actor < ApplicationRecord
validates :blood_type, inclusion: {in: ['A','B','O','AB']}
end
指定した値が含まれていないか確認するときはexclusion
を使う。
class Actor < ApplicationRecord
validates :gender, exclusion: {in: ['male','female']}
end
値の重複
値の重複がないかをチェックするための{uniqueness: true}
というバリデーションもある。
class Post < ApplicationRecord
validates :content, {uniqueness: true}
end
おまけ
複数のバリデーションの指定
バリデーションの内容はハッシュになっているので、コンマで区切ることで複数指定できる。
class Post < ApplicationRecord
validates :content, {presence: true, length : {maximum:140}}
end
自分で決めたエラーメッセージを表示する
message
を追加することで自分で指定したエラーメッセージを表示させることもできる。
class Actor < ApplicationRecord
validates :height, numericality: {greater_than: 50,less_than: 250, message: " : Please input 50~250"}
end
Author And Source
この問題について(Railsのバリデーションの種類と使い方), 我々は、より多くの情報をここで見つけました https://qiita.com/mzmz__02/items/8f4b90e98712c76a031e著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .