Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Ruby on Rails | Validation | length

概要

length

詳細

ActiveRecordで、validation時にlengthを利用することで、
最大値
最小値
範囲
固定文字数
など、文字数に関わるチェックを行うことができます。

サンプル

テーブル定義
CREATE TABLE "articles" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
  "title" varchar(255), 
  "text" text, 
  "created_at" datetime, 
  "updated_at" datetime
);
Validationその1
class Article < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  validates :title, length: { maximum: 10 }
  validates :text,  length: { minimum: 10 }
end
試行その1

rails console(pry)で試行します。

[1] pry(main)> a = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[2] pry(main)> a.title = '12345678901'
=> "12345678901"
[3] pry(main)> a.text = '123456789'
=> "123456789"
[4] pry(main)> a.valid?
=> false
[5] pry(main)> a.errors.messages
=> {:title=>["is too long (maximum is 10 characters)"],
 :text=>["is too short (minimum is 10 characters)"]}
[6] pry(main)> a.title = '1234567890'
=> "1234567890"
[7] pry(main)> a.text = '1234567890'
=> "1234567890"
[8] pry(main)> a.valid?
=> true
[9] pry(main)> a.errors.messages
=> {}
Validationその2
class Article < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  validates :title, length: { in: 3..5 }
  validates :text,  length: { is: 9 }
end
試行その2

rails console(pry)で試行します。

[1] pry(main)> a = Article.new
=> #<Article id: nil, title: nil, text: nil, created_at: nil, updated_at: nil>
[2] pry(main)> a.title = '123456'
=> "123456"
[3] pry(main)> a.text = '12345678'
=> "12345678"
[4] pry(main)> a.valid?
=> false
[5] pry(main)> a.errors.messages
=> {:title=>["is too long (maximum is 5 characters)"],
 :text=>["is the wrong length (should be 9 characters)"]}
[6] pry(main)> a.title = '12345'
=> "12345"
[7] pry(main)> a.text = '123456789'
=> "123456789"
[8] pry(main)> a.valid?
=> true
[9] pry(main)> a.errors.messages
=> {}