I have a simple phone form <%= f.text_field :phone %>
right now. :phone
is an integer type, so this requires that whatever the user enters into the form must be something like 5551234
instead of the more standard way of 555-1234
How can I allow the user to enter in a USA phone number like their accustomed to? I understand that I can use validates_format_of
to validate it, but once I validate it, how can I format the number and insert the phone number into the DB as an integer?
views:
32answers:
2
A:
"1-2-3-4".gsub('-','').to_i
# => 1234
You can also use Regular Expressions if you want to get more fancy, but you should be able to get away with just this.
You probably want to validate what you're storing it in the DB as, since Rails checks validations before saving. However, you can do a before_validation
that modifies the number first. Something like this:
before_validation do
phone = phone.to_s.gsub('-','').to_i
end
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M001378
Karl
2010-07-30 00:56:02
The only problem is that some people like to type phone numbers like `(123)555-1234` or `123-555-1234` or `(123) 555-1234`, etc. So this method doesn't quite get everything.
Reti
2010-07-30 01:35:40
In that case you could use RegEx, which are more powerful. Mark's example in his answer works beautifully.
Karl
2010-07-30 16:16:58
A:
phone.gsub(/\D/, '')
should do the trick. It removes non-digit chars.
Mark Thomas
2010-07-30 02:23:16
I put `before_validation do; phone = phone.to_s.gsub(/\D/, '').to_i; end` In my model.rb file, but it's still not changing anything.
Reti
2010-07-30 16:31:21
The regular expression works for me in irb, Ruby 1.8.7: `"(213) 456-7890".gsub(/\D/,'')=> "2134567890"`
Mark Thomas
2010-07-31 01:07:14