GithubHelp home page GithubHelp logo

validates_zipcode's Introduction

ValidatesZipcode Build Status Code Climate Gem Version security

Adds zipcode / postal code validation support to Rails (ActiveModel), considering postal code formats for mostly every country.

ValidatesZipcode currently support 233 country codes. Regex data taken from several sources, being the main source the CLDR database (release 27, around 159). Any other country's postal code will validate without errors.

ValidatesZipcode supports Rails >= 4.2 and Ruby >= 2.4. This gem could work in Rails 3.2 and Ruby 1.9.3 as well, yet unsupported; try v0.2 series if having trouble with later versions. Truffleruby is also tested, but no reports of working in production apps for now.

Installation

Add this line to your application's Gemfile:

gem 'validates_zipcode'

And then execute:

$ bundle

Or install it yourself as:

$ gem install validates_zipcode

Usage

With ActiveModel::Validations

validates_zipcode :zipcode

validates :zipcode, zipcode: true

ValidatesZipcode expects the model to have an attribute called country_alpha2 to contain the country code. You can provide your own country_code using :country_code option, or specify which attribute contains this information using :country_code_attribute option.

validates :zipcode, zipcode: { country_code: :es }

validates :zipcode, zipcode: { country_code_attribute: :my_country_code_column }

Error Messaging

If you need to localize the error message, just add this to your I18n locale file:

errors:
  messages:
    invalid_zipcode: Your zipcode error message.

You can override this on a per-model basis by passing in a :message key with the validation:

validates :zipcode, zipcode: { message: 'Your per-model zipcode error message.' }

Without ActiveModel::Validations

ValidatesZipcode.valid?('93108', 'ES')
# => true

Formatting

This gem can also be used for formatting zipcodes according to country specific rules.

ValidatesZipcode.format('Sw1A 2aA', 'UK')
# => 'SW1A 2AA'

If the zipcode is not valid an exception is raised.

ValidatesZipcode.format('Sw1A 2aA', 'FR')
# => raises ValidatesZipcode::InvalidZipcodeError

At the moment not every country is supported. See lib/validates_zipcode/formatter.rb to find all available countries.

Test data

In order to generate test data, we suggest using the regexp-examples gem This dependency will allow you to create examples as follows:

require "regexp-examples"

ValidatesZipcode::CldrRegexpCollection::ZIPCODES_REGEX[:ES].examples

# => ["00000", "00001", "00002", "00003", ..., "44443", "44444"]

ValidatesZipcode::CldrRegexpCollection::ZIPCODES_REGEX[:ES].random_example

# => "27072"

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Also, you should read and follow our Code of Conduct.

Contributors

To see the generous people who have contributed code, take a look at the contributors list.

Maintainers

License

Copyright (c) 2014 David Gil Pérez, released under the MIT license

validates_zipcode's People

Contributors

adlersantos avatar aiomaster avatar amirmingaliev avatar andychongyz avatar chloe-meister avatar devthiago avatar dgilperez avatar dimroc avatar dmitrybereza avatar droycewagner avatar ericlarch avatar geoffroh avatar gerard76 avatar harrylewis avatar johnmeehan avatar kpricorn avatar lucasfcunha avatar neerajkumar avatar northeastprince avatar nrser avatar nunosilva800 avatar ojsdude avatar pedrosfdcarneiro avatar tahanson avatar thomaschiesa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

validates_zipcode's Issues

Build test data.

I've introduced your postcode validation into our app; It's fantastic and saved us a lot of headaches!

One thing I'd like to request is that you add a helper for generating postcodes for countries as at the moment I'm using a gem to try to generate one from the regex relating to a country. This is really inconsistent and means that our tests are therefore inconsistent.

A simple object like in https://github.com/dgilperez/validates_zipcode/blob/4e8573f6ca49ccd8da667fd9b0df99366d1e6c6d/lib/validates_zipcode/cldr_regex_collection.rb with a hand full of valid entires for each country would go a long way to help us integrate this with our tests too!

Document the custom `:message` feature

Hey @dgilperez, thanks for this awesome gem. I'm currently using it at my job, and I love how easy it is to drop in postal code/zipcode validations using this.

My team is pretty deep into i18n, and have our own YAML organization for it. I noticed in 0.2.5, a feature to allow a custom message was added, which is exactly what my team needs.

My suggestion is around the documentation of this feature. Currently, it is only documented in the CHANGELOG, along with the PR itself. I had to dig around in the code to find out that this was possible.

I'm wondering if it would help others to have this documentation explicitly in the README? I'm sure many others are running custom i18n YAML file organizations, so I feel this feature is probably being used pretty heavily.

I don't mind making a PR to suggest something, if you're interested!

details hash sets :error to the message instead of the validator type

When i do

validates :post_code, zipcode: true

the record.errors[:post_code] object looks like

#<ActiveModel::Errors:0x000000057dec18 @base=#< ... post_code: "bad!", ...>, @messages={:post_code=>["Invalid ZIP / postal code"]}, @details={:post_code=>[{:error=>"Invalid ZIP / postal code"}]}>

where record.errors[:post_code].details[0] is {:error=>"Invalid ZIP / postal code"} instead of the Rails standard behvior of the "validator type" symbol (which would be :invalid_zipcode in your case) (example).

This prevents translating the error into anything other than the default locale:

# config/locales/zh-CN.yml
zh-CN:
  errors:
    messages:
      invalid_zipcode: 无效邮编号码
I18n.t "errors.messages.#{ record.errors.details[:post_code].first[:error] }", locale: 'zh-CN'
=> "translation missing: zh-CN.errors.messages.Invalid ZIP / postal code"

It's expected to produce a translation as it does with built-in validations:

I18n.t "errors.messages.#{ record.errors.details[:name].first[:error] }", locale: 'zh-CN'
=> "不能为空字符"

Is there any reason the library is using the string message instead of the "validator type" symbol?

NoMethodError: undefined method `country_alpha2' for

I followed the instruction as suggested in Readme.

In my model, I wrote

validates :zip_code, zipcode: true

But it gave an error suggesting

NoMethodError: undefined method `country_alpha2' for 

from

gems/validates_zipcode-0.0.9/lib/validates_zipcode/validator.rb:27:in `validate_each'

Is anything else which I have missed? I don't have any other validation on my model.

Validate a zip code outside validators scope

Hy again 🍻

Is there any public method available to check if a given zip code is valid in a given country?
Something like:

ValidatesZipcode.valid?(zipcode, country_code)

I'm asking this because in a user register form the zip code is also being validated in the client side with an ajax request.
And in the server, I do something like this:

!zip_code.match(ValidatesZipcode::CldrRegexpCollection::ZIPCODES_REGEX[country_code]).nil?

which, I think, it's not an ideal solution.

What do you think?

Thanks.

Invalid postal code string passes validation for United Arab Emirates

ValidatesZipcode::Zipcode.new(zipcode: "PO Box 506808", country_alpha2: "AE").valid? returns true but should return false

I've been looking around to see if the UAE even has postal codes and have seen mixed responses. For instance, this wiki page on global postal codes suggests that it does not; however, this website and this website seem to suggest that they do. Although, in either case, the string I entered above should still be invalid.

Ireland

Thanks for this awesome plugin!

Is it just me or do a lot of the Irish ZIP codes not validate?

Using Google Maps I randomly picked a few Irish codes and none of them validated:

  • X91 PK81
  • V94 H2PP
  • D07 R6YE

I also tried replacing the blanks with dashes, since some people in Ireland seem to do that. But to no avail.

Is this a bug or am I missing something really fundamental here?

I've never been to Ireland but I read that there was a major postal reform in 2015 where they introduced postal codes for the very first time.

Issue with lowercase letters in Canadian postcode

Canadian postal codes containing lower case letters are rejected as invalid:

ValidatesZipcode::InvalidZipcodeError (invalid zipcode V0H 1z6 for country CA)

I think this is because the regexp for Canada only checks capital letters. This means that the postal code will be found invalid and raise the error before reaching the formatter, which capitalises the postal code.

Am I right? If yes I'd be happy to update the regexp and submit a PR.

Japan

I think Japan doesn't work either.

Japanese ZIP codes need a dash like this:

000-0000

Or at least I couldn't find any examples on the Internet where the dash is omitted.

Validating US zipcodes at a state level

I was wondering if you'd thought about adding validation on postcodes based off of their secondary state level?

I'm thinking mainly the US, but I'd imagine there are other address zip/postal codes that are restricted further by the state, perhaps this is a secondary (optional) state/province code.

Valid UK postcode is invalid

Noticed that this UK postcode: W1K 7DA which is valid (see: https://postcodes.io/), is raising a validation error.

I've got my model configured with:

validates :postcode, zipcode: { country_code: :uk }

Do you think this is a problem with the CLDR database?
What can we do?

Validates for multiple countries.

By using the following, we are able to validate the zipcode for single country only.
validates :zipcode, zipcode: { country_code: :es }
Is there any way to validate the zipcode for multiple coutries?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.