Sha256: fc8d7c41741780bc87f1f5c513ad109e54dc98fb66eb7bff37e81d0c2bd4de32

Contents?: true

Size: 762 Bytes

Versions: 2

Compression:

Stored size: 762 Bytes

Contents

# Custom Validations for Zip Code format

# e.g. validates :zip, :zipcode_format => true
# e.g. validates :zip, :zipcode_format => { :allow_blank => true, :if => :method_returns_true }
class ZipcodeFormatValidator < ActiveModel::EachValidator
  # validates a US zipcode matching 12345, 12345 6789, or 12345-6789
  # @param [ActiveRecord::Base] record The record to validate
  # @param [Symbol] attribute The field on the record to validate
  # @param [String] value The value of the attribute
  def validate_each record, attribute, value
    format = /^\A[\d]{5}(?:[-|\s][\d]{4})?\Z$/
    message = attribute.to_s.humanize + ' doesn\'t match an acceptable format.'
    record.errors[attribute] << (options[:message] || message ) unless value =~ format
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
format_validators-0.0.8 app/validators/zipcode_format_validator.rb
format_validators-0.0.7 app/validators/zipcode_format_validator.rb