Question

We're looking for a way to standardize the entry of phone numbers entered in a form to be, for example, (444) 555-666. Right now you can enter it as any format, such as 4445556666 or 444-555-6666 and there's no standardization. I'd like a way for the number to be converted to the former format when it's entered into the database.

Here is the HTML code for the form:

<tr>
  <td align="right">
    <label for="phone_number">Telephone:</label>
  </td>
  <td>
    <input type="text" name="phone_number" value="#form.phone_number#" />
  </td>
</tr>

This, along with all other data, is entered into the database using a cfquery INSERT INTO command. I can provide that code if needed. Here's an abbridged version:

INSERT INTO Schedule_Registrations(
  phone_number
)
VALUES(
  '#FORM.phone_number#'
)

Any thoughts on this would be appreciated.

Was it helpful?

Solution

The way I've chosen to deal with this issue is to store raw numbers in the database, and then display them how I want on a web page. To normalize the numbers, use a simple regex:

<cfset cleanPhoneNumber = reReplace(form.phoneNumber, "[^0-9]", "", "ALL")>

Store cleanPhoneNumber in the database, and then use a simple format function to display it:

<cffunction name="formatPhoneNumber">
    <cfargument name="phoneNumber" required="true">

    <cfif len(phoneNumber) EQ 10>
        <!--- This only works with 10-digit US/Canada phone numbers --->
        <cfreturn "(#left(phoneNumber, 3)#) #mid(phoneNumber, 4, 3)#-#right(phoneNumber, 4)#">
    </cfif>

    <cfreturn phoneNumber>
</cffunction>

The challenge is that outside the US there is not a standardized way to format numbers (that I've found). Also be careful if you allow a user to enter an extension in the phone number field.

OTHER TIPS

I liked Scott's approach. So I combined it and made a function for <cfscript>

string function formatPhone(required string phoneNumber) output="false"    {

    arguments.phoneNumber = reReplace(arguments.phoneNumber, "[^0-9]", "", "ALL");

    if (len(arguments.phoneNumber) == 10)   {
        return "(#left(arguments.phoneNumber, 3)#) #mid(arguments.phoneNumber, 4, 3)#-#right(arguments.phoneNumber, 4)#";
      }

    return arguments.phoneNumber;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top