Skip to content

Instantly share code, notes, and snippets.

@backpackerhh
Last active September 16, 2019 15:53
Show Gist options
  • Select an option

  • Save backpackerhh/1e89bc49884675cf018d to your computer and use it in GitHub Desktop.

Select an option

Save backpackerhh/1e89bc49884675cf018d to your computer and use it in GitHub Desktop.

Revisions

  1. backpackerhh revised this gist May 19, 2014. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion spanish_postal_code_validator.rb
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,8 @@
    #
    # class MyClass < ActiveRecord::Base
    # ...
    # validate :postal_code, spanish_postal_code: true
    # validate :postal_code, spanish_postal_code: true # default message
    # validate :postal_code, spanish_postal_code: { message: '<Your message>' } # custom message
    # ...
    # end
    #
  2. backpackerhh created this gist May 17, 2014.
    15 changes: 15 additions & 0 deletions spanish_postal_code_validator.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    # Usage:
    #
    # class MyClass < ActiveRecord::Base
    # ...
    # validate :postal_code, spanish_postal_code: true
    # ...
    # 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