Allows you to easily format and validate phone numbers in your desired format (sensible defaults provided).
Just add ‘validates_and_formats_phones’ to your ActiveRecord model.
The default format is a 10-digit US phone number on the column ‘phone’. But you can change all that…just read on.
-
Install it as a gem:
(sudo) gem install validates_and_formats_phones
-
Then add it to your
Gemfile
filegem 'validates_and_formats_phones', '~> 1.0.0'
-
Add the method
validates_and_formats_phones
to your model
Adding the validates_and_formats_phones method by itself gives you validation and formatting for the field :phone like so:
class Person validates_and_formats_phones end > person = Person.new(:phone => '123 456 7890') > person.save > person.phone > => '(123) 456-7890' > > person.phone = '123' > person.save > => false
You can pass your own fields like so:
class Person validates_and_formats_phones :fax, :mobile end
Or your own formats by using a # symbol for number substitutions:
class Person validates_and_formats_phones '####-####', '### ###-####' end
Note that the validation is simplistic. It counts the number of digits in the given field. If the number of digits in the given field matches one of the formats, then the validation passes and the format that has the same number of ‘#’ symbols will be used to format the phone number.
You can also format and specify fields, like so:
class Person validates_and_formats_phones :fax, mobile, '####-####' end
All configuration options available to validates_each are also available to the phone validator. For example:
class Person validates_and_formats_phones :fax, '###-###-####', :if => :some_function_name end
Here’s a quick link to the validates_each documentation at the time of writing:
http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates_each
As a tiny added benefit, String is extended with a to_phone method.
> '123 456 7890'.to_phone > => '(123) 456-7890' > > '12345678'.to_phone('####-####') > => '1234-5678'
1.0.0 No significant changes. 0.0.10 1. Make compatible with Rails 3 (note this breaks compatibility with previous Rails versions) 0.0.7 1. Bug fix for ...yes... Ruby 1.8.5...That's dedication right there. 0.0.6 1. Add configuration options available in validates_each method.
If you find any bugs, please report them at our github page:
http://github.com/btelles-validates_and_formats_phones
Copyright © 2010 [Bernie Telles], released under the MIT license