Sha256: f15bf96f3e52c0cbf99e0a9875fa19630d9fd23d4807bdada6e697a04a8f9103

Contents?: true

Size: 1 KB

Versions: 5

Compression:

Stored size: 1 KB

Contents

# Usage:
#
# class User < ActiveModel
#   validates :postalcode, zipcode: true
#
#   # Default country_alpha2 attribute.
#   # You can change it using :country_code_attribute option
#   def country_alpha2
#     country.alpha2
#   end
# end
#

require 'active_model'
require 'active_model/validator'

module ValidatesZipcode
  class Validator < ActiveModel::EachValidator
    include CldrRegexpCollection

    def initialize(options)
      @country_code = options.fetch(:country_code) { }
      @country_code_attribute = options.fetch(:country_code_attribute) { :country_alpha2 }

      super
    end

    def validate_each(record, attribute, value)
      alpha2 = @country_code || record.send(@country_code_attribute)
      regexp = regexp_for_country_alpha2(alpha2)
      return unless regexp

      unless regexp.match(value.to_s)
        record.errors.add(attribute, I18n.t('errors.messages.invalid_zipcode', value: value))
      end
    end
  end
end

ActiveModel::Validations::ZipcodeValidator = ValidatesZipcode::Validator

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
validates_zipcode-0.0.7 lib/validates_zipcode/validator.rb
validates_zipcode-0.0.6 lib/validates_zipcode/validator.rb
validates_zipcode-0.0.5 lib/validates_zipcode/validator.rb
validates_zipcode-0.0.4 lib/validates_zipcode/validator.rb
validates_zipcode-0.0.3 lib/validates_zipcode/validator.rb