Skip to content

Instantly share code, notes, and snippets.

@hjblok
Created January 13, 2010 18:51
Show Gist options
  • Save hjblok/276455 to your computer and use it in GitHub Desktop.
Save hjblok/276455 to your computer and use it in GitHub Desktop.
# config/environment.rb
require "open-uri"
config.gem "nokogiri"
# app/models/your_model.rb
# Expects postal_code, street and city to be part of your model:
# Address.postal_code = "1222 AX"
# Address.street = "Erfgooiersstraat"
# Address.city = "Hilversum
# Address validation based on the postal_code database from 6pp (http://kvdb.net/projects/6pp/):
# - streetname in the 6pp database should match Address.street
# - cityname in the 6pp database should match Address.city
validate :valid_address
def valid_address
valid_city = valid_street = false
if postal_code =~ /^[1-9]{1}[0-9]{3} ?[A-Z]{2}$/
pc = postal_code.gsub(/ /,"")
sixpp = Nokogiri::HTML(open("http://6pp.kvdb.net/services/lookup?postcode=#{pc}"))
sixpp.xpath("//city").each {|c|
valid_city = true if !c.content.empty? && city =~ /^#{c.content}/i
}
sixpp.xpath("//street").each {|s|
valid_street = true if !s.content.empty? && street =~ /^#{s.content}/i
}
end
errors.add(:city, "doesn't match postal code") unless valid_city
errors.add(:street, "doesn't match postal code") unless valid_street
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment