Class: OmgValidator::Validators::PostalCodeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/omg_validator/validators/postal_code_validator.rb

Overview

Checks whether input is a valid postal code

Matches:

L2J 4T5, l2a 9d1, h2o 4g1, h2o4g1

Does not match:

z2n 1n3, aan 2j2, LL2J 4T5, 5j4 f1d

Examples:

validates :postal_code, postal_code: true

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/omg_validator/validators/postal_code_validator.rb', line 14

def validate_each(record, attribute, value)
  return nil if value.blank?
  reg = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/i
  unless reg.match(value)
    record.errors[attribute] = "must be a valid postal code"
  end
end