0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

config/initializersにカスタムバリデータを定義する

Last updated at Posted at 2020-02-04

電話番号にバリデーションを使用する

telephone_numberというgemを使用してカスタムバリデーションを定義する。

まずはgemを定義

gem 'telephone_number'

そしてbundle install!

$ bundle

config/initializeに下記のように定義

config/initializers/tel_validator.rb

module ActiveModel
  module Validations
    class TelValidator < EachValidator
      def validate_each(record, attribute, value)
        return if value.blank?

        record.errors.add attribute, :invalid unless TelephoneNumber.valid?(value, :jp)
      end

      module HelperMethods
        def validates_tel_of(*attr_names)
          validates_with TelValidator, _merge_attributes(attr_names)
        end
      end
    end
  end
end

そしてあとは個別のモデルで下記のようにすれば電話番号のバリデーションがかかってくれる。

hoge.rb
validates :tel, tel: true

参考記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?