Forum: Ruby on Rails Phone format in Rails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
cool (Guest)
on 2009-03-02 09:53
(Received via mailing list)
Guys,

     I have a text field and the name is phone
    I used to enter contact number.
   In the new form when i enter 10 digit number like "1234567890" it
is displaying 1234567890
  I want to display like in US format automatically like "(123)
456-7890".
   I need to provide validation for that field also.
Can u help me how can i do that.
  Very badly i need a help. i am struck with this issue......
Priya B. (Guest)
on 2009-03-02 11:04
cool wrote:
> Guys,
>
>      I have a text field and the name is phone
>     I used to enter contact number.
>    In the new form when i enter 10 digit number like "1234567890" it
> is displaying 1234567890
>   I want to display like in US format automatically like "(123)
> 456-7890".
>    I need to provide validation for that field also.
> Can u help me how can i do that.
>   Very badly i need a help. i am struck with this issue......

validates_format_of :phone, :with => ((\(\d{3}\) ?)|(\d{3}[-
\.]))?\d{3}[- \.]\d{4}(\s(x\d+)?){0,1}$
MaD (Guest)
on 2009-03-02 11:08
(Received via mailing list)
you could simply write your own helper like that:

  def format_phone_number(number)
    return "(#{number[0..2]})#{number[3..5]}-{number[6..-1]}"
  end

add it to your view_helper and call it whenever you like.

validations are similar. just add your own validation.
pepe (Guest)
on 2009-03-03 05:54
(Received via mailing list)
I'm not sure the type of validation you need on the field. This is
something simple I did for an application I wrote:

    phone =~ /^\d{10}$/ && phone.to_i >= 999999999

This will make sure that the string contains only 10 digits (/^\d
{10}$/) and that the 10 digits are miningful or the number doesn't
start with a 0 (>= 999999999).

About the formatting of the string, rails has tons of helpers, and the
one you're looking for is number_to_phone:

<%= number_to_phone(1234567890, :aea_code => true, :delimiter => ' ')
%> # (123) 456-789
pepe (Guest)
on 2009-03-03 05:56
(Received via mailing list)
Sorry, made a mistake, the result of number_to_phone would be (123)
456-7890 (I missed the 0).

And about the number of digits, I said \d{10} makes sure the string
contains only 10 digits. What I meant is that the string will have to
contain a total of 10 digits, no more, no less.

Pepe
This topic is locked and can not be replied to.