Forked from backpackerhh/spanish_postal_code_validator.rb
Created
September 16, 2019 15:53
-
-
Save Altons/d5ee1120cc0adb59ddac8bfd2a254d8b to your computer and use it in GitHub Desktop.
Spanish postal code validator for Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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