Ruby on Rails phone number validation
Tuesday, 20 January, 2009 — software rails testing
I recently launched a Rails application that has a phone number field available to it. In the process of writing my spec tests, I allowed the phone field to be a certain number of characters and allowed it to be empty. The formatting test, however, I left pending. I searched for, but did not find a great solution past some very unreadable regular expressions.
In the course of watching a movie this evening, I had a solution. I created an array of acceptable formats, looped over the array and checked each entry against the phone number. If I had a match, the validation passes. Setting the string match to the beginning and I can allow for extensions without being too persnickety about formatting.
Here it is (via a handy gist):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
def valid_phone return true if phone.blank? phone_formats = [ /^\(\d\d\d\) \d\d\d-\d\d\d\d/, /^\d\d\d\.\d\d\d\.\d\d\d\d/, /^\d\d\d\-\d\d\d\-\d\d\d\d/ ] valid = false phone_formats.each do |format| if phone.match( format ) valid = true end end unless valid errors.add("Phone format isn't recognized") end end
Here are some spec test examples.
It doesn’t handle international formats, but, for right now, it fits my needs.