I was using phony to format phone numbers (meaning, if I put in xxx-xxx-xxxx it would convert to a string, and also tell if there is a (1) before to remove it).
But
I wrote this regex to match NANPA phone numbers with some conventions (e.g. for extensions) for PHP (thank god those days are over) and converted it over to a Rails validator a few months ago for a project. It works great for me, but it is more pragmatic than strictly to spec.
# app/validators/phone_number_validator.rb
class PhoneNumberValidator < ActiveModel::EachValidator
@@regex = %r{\A(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?:ext|x)\.? ?(\d{1,5}))?\Z}
def validate_each (object, attribute, value)
if m = value.match(@@regex)
# format the phone number consistently
object.send("#{attribute}=", "(#{m[1]}) #{m[2]}-#{m[3]}")
else
object.errors[attribute] << (options[:message] || "is not an appropriately formatted phone number")
end
end
end
# app/models/foobar.rb
class Foobar < ActiveRecord::Base
validates :phone, phone_number: true
end
The saved/outputted format is like this: (888) 888-8888. Currently the output strips off the extension because I didn't need it. You can add it back in and change the format pretty easily (see the object.send line.