Rails - Convert phone numbers to international format for SMS

This post will show you how to convert almost any phone number into a consistent and reliable international format that can be used to send SMS messages.

If you have an application where users can enter in phone numbers, and you need those phone numbers in international format for sending sms messages to, it can be a challenge. This is a solution that allows you to keep the numbers in the format the user entered it in, and doesn't force the user to understand international dialling codes.

I utilised two great gems for this technique, they are:

I had nothing to do with those gems, all credit goes to the authors.

To convert the phone numbers, I use this method, you could create it as a helper, or have a SMS or Phone class for it:

 def self.internationalize_phone_number(number, country)
  c = Country[Country.find_by_name(country)[0]]
  if c
    number = Phony.normalize(number)
    number = "#{c.country_code}#{number}" unless number.starts_with?(c.country_code)
  end
  number = Phony.normalize(number)
  number
end

You need to pass in the number to be formatted, and also the country of the recipient (the country takes the parameter as "Australia", "United Kingdom", "United States", etc). If you want to pass the country code as "AU", "GB", "US", etc. you could simplify line 2 of the code, as the countries gem prefers that format.

Most of the heavy lifting is done by the Phoney gem. I first normalize the number that has been passed in to remove any extra characters like brackets or +.

Once this is done, I add the country code (as found from the countries gem) to the start of the number, only if the number doesn't already start with the country code.

Finally I normalize the number again with Phoney, this will remove any redundant zero's after the country code (the first normalize would not have done this, because it wasn't redundant without the area code). The first normalize is required though so that we can properly check if the starting characters are the country code.

With this small function, the following conversions would take place:

  • 0400 000 000, Australia -> 61400000000
  • +61 400 000 000, Australia -> 61400000000
  • +61 0400 000 000, Australia -> 61400000000
  • (+61) 400 000 000, Australia -> 61400000000
  • 07 000 000 000, United Kingdom -> 447000000000
  • +44 07 000 000 000, United Kingdom -> 447000000000

This is just a small set of examples that are taken care of.

Once again, credit goes to the authors of the above mentioned gems, their hard work made this so easy.

By Joel Friedlaender