Jakob Skjerning 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 Skjerning - 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%>
<label for="client_phone_number">Phone Number</label>
<%= 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
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---