LoginSignup
1
0

More than 5 years have passed since last update.

NULL は許可するが空文字や空白文字は許可しないようにバリデーションを実装する

Last updated at Posted at 2018-09-11

方法

class Anime < ApplicationRecord
  # 正規表現で空文字あるいは空白文字だけで構成された文字列を許可しないようにする。
  # 加えて allow_nil オプションを有効にして NULL は許可する。
  validates :title, format: { without: /\A[[:space:]]*\z/, allow_nil: true }
end

Anime.new(title: nil).valid? #=> true
Anime.new(title: 'Fate/stay night').valid? #=> true

Anime.new(title: '').valid? #=> false
Anime.new(title: ' ').valid? #=> false
Anime.new(title: ' ').valid? #=> false
Anime.new(title: "\r\n").valid? #=> false
Anime.new(title: "\t").valid? #=> false

正規表現中の [[:space:]] は POSIX 文字クラスと呼ばれる表記で空白文字を表します。

参考

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