How to remove spaces from phone number

Hi,

I need to allow login based on the phone number. During the signup they
can give the number in any format with spaces, slash or (). But for
storing in database and then during login to compare I just want the 10
digit number. How can I remove the special char from phone number before
storing to db ?

Thanks.

Rm Rm wrote:

I need to allow login based on the phone number. During the signup they
can give the number in any format with spaces, slash or (). But for
storing in database and then during login to compare I just want the 10
digit number. How can I remove the special char from phone number before
storing to db ?

before_save {|o| o.phone_number.gsub!(/\D/, “”)

or something like that. I don’t recall if before_save accepts a block
like that, though. If it doesn’t just create a named method instead and
call that from before_filter.


Jakob S. - http://mentalized.net

Jakob S. wrote:

Rm Rm wrote:

I need to allow login based on the phone number. During the signup they
can give the number in any format with spaces, slash or (). But for
storing in database and then during login to compare I just want the 10
digit number. How can I remove the special char from phone number before
storing to db ?

before_save {|o| o.phone_number.gsub!(/\D/, “”)

or something like that. I don’t recall if before_save accepts a block
like that, though. If it doesn’t just create a named method instead and
call that from before_filter.


Jakob S. - http://mentalized.net

Here is how I solved this problem.

In your model, put the following:

class Client < ActiveRecord::Base

validates_numericality_of :phone_number
validates_length_of :phone_number, :is => 10

before_validation :normalize_phone_number # this gets called
first

def normalize_phone_number
self.phone_number.gsub!( /[\s()-]/, ‘’ ) # cleans out the junk
end
end

Now to get this to display nicely, I used the helper number_to_phone.

<%= number_to_phone @client.phone_number, :area_code => true %>

If this is in a form and needs be edited, I do something like this:

<%= start_form_tag :action => ‘update’, :id => @client%>

Phone Number

<%= text_field ‘client’, ‘phone_number’, :value => number_to_phone(
@client.phone_number, :area_code => true ), :size=> 20 %>


<%= submit_tag ‘Save’ %>
<%= end_form_tag %>

Note: I used the older start_form_tag convention, but I think it should
also work with the newer form_for convention as well.

Hope this helps.

Mike

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs