Validating and Formatting a Phone Number

Validating and Formatting a Phone Number

any of the more common questions asked of the VB Pro involve formatting and validating data. In this 10-Minute Solution, you’ll learn how to validate and format a phone number. While we won’t deal with international (non-US) phone numbers here, you can apply these techniques to your local phone number format.

In the United States, there are a number of valid formats for phone numbers that might be entered into a form:

nnn-nnnnnnn-nnn-nnnn1-nnn-nnn-nnnn1-nnn-nnnnnnn-nnnn xnnnn

There are many other variations of this, as well, but those examples should be enough to give you an idea of what we’re dealing with here. Because there are so many valid formats, you’re going to have to set some rules for reformatting these phone numbers:

1. All numbers will at least be in the format (nnn) nnn-nnnn. Numbers entered without area codes will have a default area code prepended to them.

2. Any extensions will be listed as xnnnnn following the phone number.

3. If an initial 1 is added to the number, it will be removed, since users already know to dial a one before making a long distance call.

With these rules in mind, let’s create the validation code for a text box named txtPhone:

Private Sub txtPhone_Validate(Cancel As Boolean)   Dim strTemp As String   Dim strPhone As String   Dim strExtension As String   Dim intResult As Integer      Const DefaultAreaCode = "703"   '   ' Remove all the grouping characters for   ' now. We'll add them back in later.   '   strTemp = Replace(txtPhone, "(", "")   strTemp = Replace(strTemp, ")", "")   strTemp = Replace(strTemp, "-", "")   strTemp = Replace(strTemp, " ", "")   strTemp = Replace(strTemp, "X", "x")      '   ' Break up the digits into the number and   ' the extension, if any.   '   intResult = InStr(1, strTemp, "x", vbTextCompare)   If intResult > 0 Then      strExtension = Mid(strTemp, intResult + 1)      strPhone = Left(strTemp, intResult - 1)   Else      strPhone = strTemp   End If      If Left(strPhone, 1) = "1" Then      strPhone = Mid(strPhone, 2)   End If      If Len(strPhone) <> 7 And Len(strPhone) <> 10 Then      MsgBox "Please enter a valid telephone number.", vbExclamation	Cancel = True      Exit Sub   End If      '   ' Prepend the default area code   '   If Len(strPhone) = 7 Then      strPhone = DefaultAreaCode & strPhone   End If      '   ' Build the new phone number   '   txtPhone = "(" & Left(strPhone, 3) & ") " _      & Mid(strPhone, 4, 3) & "-" _      & Right(strPhone, 4)      '   ' Add the extension, if any   '   If strExtension <> "" Then      txtPhone = txtPhone & " x" & strExtension   End If   End Sub

I used a default area code of 703, which you can obviously change as needed. If you’re going to be using the application in different locations, you may want to store that information with the application user’s profile, similar to the way that Windows stores your favorite locations for dialing.

The code first removes all the grouping and separator characters, except for the X, which marks the beginning of an extension. It was best to convert uppercase X’s to lowercase x’s for purposes of comparison.

Next, the code parses out the phone number and the extension. If there is a leading 1, it’s removed. The phone system is such that you can’t have a 1 as the first number of either an area code or a phone number prefix.You will then either have a ten-digit phone number or a seven-digit phone number. If you don’t have either one, you have an error and bail out immediately.

For seven-digit phone numbers, we prepend the default area code, and then build the final number with a little bit of string manipulation. The extension found, if any, is added back to the number. To try this code out, you can use any of these test cases to see the validation in action:

  • 5551212?will prepend 703 and create (703) 555-1212.
  • 15551212?same result as previous case.
  • 5551212 x 1 2 3 4?becomes (703) 555-1212 x1234?spaces are removed.
  • 17035551212 x 1234?same as previous case.
  • Any numbers that aren’t seven or 10 digits?trapped error.

The end result is that it makes data entry easier for the user. The computer is now smart enough to automatically translate data into the format that has been pre-selected for use in that system, saving time?and no doubt?money.

devx-admin

devx-admin

Share the Post:
iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years,

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW)

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will