Class: ZipCodeFormatValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/zip_code_format_validator.rb

Overview

Validates that a value is formatted as a US ZIP code or similar alphanumeric postal code.

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, value) ⇒ void

This method returns an undefined value.

Validates a single attribute value against the ZIP code pattern.

Parameters:

  • object (ActiveModel::Model)

    the record being validated

  • attribute (Symbol)

    the attribute name

  • value (String, nil)

    the value to validate



11
12
13
# File 'app/validators/zip_code_format_validator.rb', line 11

def validate_each(object, attribute, value)
  object.errors.add attribute, (options[:message] || "is not formatted properly") unless /(?i)^[a-z0-9][a-z0-9\- ]{0,10}[a-z0-9]$/.match?(value)
end