Phone format in Rails


#1

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…


#2

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}$


#3

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.


#4

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


#5

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