Share
Explore BrainMass

Algorithm to validate a US phone number (xxx) xxx-xxxx

Design an algorithm (no code) just using if-then statement or while statement generically, that validates a US phone number in the form of (xxx) xxx-xxxx.

In many situations, information is supplied as a string of text characters. The characters of that information may need to be in a particular format to be valid. Common examples include credit card numbers, e-mail addresses, dates, and telephone numbers.

Develop an algorithm to verify if a string of characters could represent a valid U.S. phone number. Since determining whether a string of characters is actually a valid phone number is a complex process. Therefore, you will determine only if the characters in the string appear in a format appropriate for such a phone number.

The algorithm should accept any string in the form (xxx) xxx-xxxx, where x represents a digit and the other characters represent themselves, and reject all others. For this algorithm, you can determine the total number of characters in the string and inspect the value of one character at a time.

Provide an example of an input string that is in the proper format and an example that is not in the proper format. Describe how your algorithm determines that the first string is in the proper format and that the second string is not in proper format.

Attachments

Solution Preview

Please consider this response as a mere guidance for you and use it for understanding the logic. Express it in your own words/style/format in case you want to use it for submission.

procedure checkPhoneNumber
Input: String phoneNumber
Output: Boolean value OK or NotOK

// Assumption: A valid phone number is exactly 14 characters long as per the format "(xxx) xxx-xxxx"
// where x indicates a digit.

Step 1: Check the length of input (argument) phone number.

if (stringLength(phoneNumber) != 14)
return NotOK

// Reaching here means input phone number is exactly 14 characters ...

Solution Summary

Algorithm is composed of three steps. Solution considers 3 cases of improper format US phone numbers to illustrate failure at each of these steps, and a case of proper format US phone number.

$2.19