Help us understand the problem. What is going on with this article?

Rails 4 でバリデータを自作する(custom validator)

More than 5 years have passed since last update.

Rails 4 でカスタムバリデータを作成する方法です。以下のページを参考にしています。

1. app ディレクトリ内に validators というディレクトリを作成します

$ cd <RAILS_ROOT>
$ mkdir app/validators

2. カスタムバリデータを作成し、app/validators ディレクトリに保存します

Ruby on Rails Guides が参考になります。
今回は Email 用のバリデータ(EmailValidator)を作成します。

app/validators/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

3. カスタムバリデータを有効にするため config/application.rb を修正します

config/application.rb の config.autoload_paths にカスタムバリデータを置いてあるディレクトリパスを追加すると、カスタムバリデータが必要な時に自動的に読み込まれるようになります。

config/application.rb
# ...
module Core
  class Application < Rails::Application
    # ...

    # add custom validators path
    config.autoload_paths += Dir["#{config.root}/app/validators"]

    # ...
 end
end

4. バリデータを利用したい Model でカスタムバリデータを有効にします

app/models/user.rb
class User < ActiveRecord::Base
  # ...
  validates :email, email: true # <- カスタムバリデータ(EmailValidator)
  # ...
end

validates で email: true を指定することで、先ほど作成した EmailValidator の validate_each が呼ばれます。

参考 URL

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした