Wednesday, 26 March 2008

Validates As EU VAT Number Rails plugin published

I've extracted the validation routines into a plugin that checks an ActiveRecord attribute to see if it conforms to the correct format for a VAT number. It works with all the EU countries and is tested with real EU VAT numbers as harvested from the good ol' Interweb.

Install

Install via script/plugin

script/plugin install http://accounts4free.rubyforge.org/svn/plugins/validates_as_eu_vat_number


or use piston

piston import http://accounts4free.rubyforge.org/svn/plugins/validates_as_eu_vat_number


Usage

The plugin provides another validation helper validates_as_eu_vat_number which takes a set of attributes and an optional :with modifier that points to the attribute containing the country code, or a string containing the country code itself. If you don't use the :with modifier then the routine expects the country code to be the first two characters of the attribute itself, e.g:

  class VatNumber < ActiveRecord::Base
validates_as_eu_vat_number :full_vat_number
validates_as_eu_vat_number :vat_number,
:with => :country_code
end


In common with other validates plugins, this one takes the usual :if, :unless, :on, :message, :allow_nil and :allow_blank options provided by the underlying validation mechanism.

Documentation

The plugin has rdoc documentation included. Run rake within the plugin directory to create it.

Testing

ValidatesAsEuVatNumber has an extensive test suite created using Rspec and a lot of Googling for VAT numbers. The easiest way to run the test suite is to do rake spec:plugins from the root directory of the Rails application containing the plugin (and the rspec and rspec_on_rails plugins as well obviously).

Freebies

The plugin creates an EU module with a couple of constants in it.

EU::MEMBER_STATES_COUNTRY_CODES is an array containing the ISO code strings of all the EU member states.
EU::MEMBER_STATES_VAT_PICTURES is a hash indexed on the country code containing the Regular expression VAT pictures for every EU country .

Links

If you're looking for a VAT validator but not working with Rails then you might want to try this Javascript validator
And if you just want to check a VAT number to see if it is live, then use the online checker on Europa.

Bugs/Comments/Faint Praise

Let me know