Related Posts

Archive

Rails and Normalizing Phone Numbers

October 28th, 2008

Rails has this interesting function number_to_phone. Given the correct data, the string “19876543210″), it can format it nicely (to the string “1 (987) 654-3210″).

Problem is, how do you correctly format (aka normalize) people’s input? People will enter phone numbers with whatever format they feel is appropriate.

First, lets show them the preferred format.

app/views/yourmodel/new.rb && app/views/yourmodel/edit.rb
<dl class="form">
<dt><%= f.label :phone %></dt>
<dd><%= f.text_field :phone, :value => number_to_phone(@yourmodel.phone, :area_code => true) %></dd>
</dl>

Now, We need to intercept it at some point before it gets into the database (See Graeme Mathieson’s writup for the other possible way to do this)

app/models/yourmodel.rb
before_validation :normalise
 
def normalise
phone.gsub!(/[^\d]/, “”) if !phone.nil?
end
 
validates_format_of :phone,
:with => /^1?(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/i,
:message => “Invalid Phone number”,
:if => :phone?

Posted in Ruby |

Comments are closed.

Previous post: Hide form sections in Prototype: “.display-switch”

Next Post: Change file character encoding