In order to be more user friendly and make our forms as easy as possible to fill out, we’ve decided to combine email and phone number fields within our forms to be a single field and let the user decide which method of contact they prefer to give us quickly and easily. The field is required because the whole purpose of the forms is to get contact information.
Requiring the field in Rails is easy, simply add the following in the model:
validates_presence_of :phone_or_email |
where :phone_or_email is the name of the field.
But how to validate at least the email address format or the phone number format? And to make it a truely user friendly form, allow the user to enter the phone number in any format they wish as long as it has a valid phone number. In other words, let the user use spaces, dashes or periods; let the user use parentheses to denote area code or leave them off if they wish; and let the user include or exclude the 1 at the beginning.
Here’s the rails code I added to my model to get this working and it seems to be pretty solid! Feel free to use this code in your app and if you happen to be an expert in regular expressions and want to give me pointers on how to clean it up a bit, please comment below!
validates_format_of :phone_or_email, :with => /^([a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]|[1]?[\-|\s|\.]?\(?[0-9]{3}\)?[\-|\s|\.]?[0-9]{3}[\-|\s|\.]?[0-9]{4})$/, :message => "is not a valid phone number (incl. area code) or email address" |
(Keep in mind that the company I work for does not currently do business outside the US, so I’m not interested in supporting foreign phone numbers and prefixes)