Posted tagged ‘regex’

A Kinder, Gentler Phone Number Validation

March 12, 2008

Since the very promising phone_validation plugin from Savvica is not yet done, I threw together a validation that is both super simple for the developer and very kind to the user. I’m sick of web sites that require phone numbers (or credit cards) to be entered as numerals only. That’s just not the way we normally write phone numbers (or credit card numbers), so we shouldn’t be forced to enter them that way on a web site.

My approach allows the user to enter a number between 10 and 20 digits (to allow for longer international numbers, and for punctuation) along with hyphens, periods, parentheses, and spaces. So any of the following would be allowed:
7345551212
734-555-1212
(734) 555-1212
734.555.1212
)(73-4-5551212
etc.

Of course the last one mentioned is not something you’d expect, but it’s allowed, since I don’t bother only limiting the punctuation to specific places. I built the regex with North America and the Caribbean in mind, but allowed longer numbers to account for international differences. (I whipped this together in a very short time… if you want to request changes for internationalization, let me know exactly how your needs differ from what this provides.)

Additionally, this allows for an extension to be included in the number, in a variety of ways:
734-555-1212 x 123
734-555-1212 x. 123
734-555-1212 ex. 1235
734-555-1212 EXT. 12
734-555-1212 eXteNsion 12345
etc.

If the full word “extension” is used, the period is not allowed. The letters of the word could be scrambled, although no one is likely to do that.

  validates_format_of :home_phone, :work_phone, 
    :message => "must be a valid telephone number.",
    :with => /^[\(\)0-9\- \+\.]{10,20} *[extension\.]{0,9} *[0-9]{0,5}$/i 

The things you might want (or need) to change are the number of digits accepted (from 20 to whatever), the word for “extension” and the length of the word (currently 9), and the number of digits allowed for an extension.

If you want to disallow extensions, just change it to:

  validates_format_of :home_phone, :work_phone, 
    :message => "must be a valid telephone number.",
    :with => /^[\(\)0-9\- \+\.]{10,20}$/ 

Advertisements