Class: Validatious::Validators::PostalCodeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Validatious::Validators::PostalCodeValidator
show all
- Defined in:
- lib/validatious/validators/postal_code_validator.rb
Overview
Active Model Postal Code Validator
Instance Method Summary
collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
# File 'lib/validatious/validators/postal_code_validator.rb', line 7
def validate_each(record, attribute, value)
countries = options[:country].is_a?(Array) ? options[:country] : [options[:country]]
countries = countries.map do |name|
country = case
when name.is_a?(Symbol)
record.send name
when name.is_a?(Hash)
c_obj = record.send(name.keys.first)
c_obj ? c_obj.send(name[name.keys.first]) : nil
else
name.blank? ? 'USA' : name
end
regex = nil
Validatious::Addresses::Countries.countries.each do |config|
if country =~ /^(#{config[:name]}|#{config[:alpha2]}|#{config[:alpha3]})$/i
regex = config[:postal_code]
break
end
end
regex
end.compact
if countries.empty?
record.errors.add :base, "A valid country must be provided for " +
"#{attribute.to_s.humanize.downcase} validation."
else
valid = countries.map do |regex|
!(value.to_s =~ /^#{regex}$/i).nil? ? true : nil
end.compact
record.errors.add attribute, :invalid_postal_code, options if valid.empty?
end
end
|