Skip to content

Instantly share code, notes, and snippets.

@backpackerhh
Last active September 16, 2019 15:53
Show Gist options
  • Save backpackerhh/1e89bc49884675cf018d to your computer and use it in GitHub Desktop.
Save backpackerhh/1e89bc49884675cf018d to your computer and use it in GitHub Desktop.
Spanish postal code validator for Rails
# Usage:
#
# class MyClass < ActiveRecord::Base
# ...
# validate :postal_code, spanish_postal_code: true # default message
# validate :postal_code, spanish_postal_code: { message: '<Your message>' } # custom message
# ...
# end
#
class SpanishPostalCodeValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /\A(0[1-9]|[1-4][0-9]|5[0-2])\d{3}\z/i
object.errors[attribute] << options.fetch(:message, I18n.t('errors.messages.invalid'))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment