Module: ActiveModel::Validations::HelperMethods

Defined in:
lib/active_model/validations/postcode_validator.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#validates_as_postcode(*attr_names) ⇒ Object

Validates whether the value of the specified attribute is a valid zip code

class Address < ActiveRecord::Base

  validates_as_postcode :zipcode, country: :US

  validates :post_code,
    presence: true,
    postcode: { allow_nil: true, country: -> { |record| record.country_code } }
end

Configuration:

  • :country - The ISO-3166-2 code of the country we will validate the zip code for. Can be a static value or a lambda that may accept the current record as its first argument.



48
49
50
# File 'lib/active_model/validations/postcode_validator.rb', line 48

def validates_as_postcode(*attr_names)
  validates_with PostcodeValidator, _merge_attributes(attr_names)
end