0

My objective is to see if the user puts in a valid phone number once. If not, I just tell them its wrong. I've looked at How to format a string as a telephone number in C# and some others, but im still not sure.

What I need to do, is make sure the user puts in a valid number meaning 1) it can only be numbers 2) the dashes must be in the right place and 3) its the right amount of characters.

I did the 3rd one. And number 1 should just be a TryParse validation.. I am mostly figuring out number 2. Is the above question correct about doing something like:

string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);

Now, this shows .Format. I don't think I need that because I am only supposed to validate if a number is formatted correctly, not to actually put the numbers in between dashes.

So, the end result would be Please enter number: 123-456-7890 Congrats this number is valid

or

Please enter number: 123-45-45-4 This number is not valid.

Avoid using Regex solutions and the number does NOT have to be real. Just as long as it fits the format above.

Community
  • 1
  • 1
Xoax
  • 77
  • 4
  • 13
  • 2
    Look into regular expressions – Oliver Sep 22 '16 at 22:54
  • Hmm, as programmers it is our job to make the life of people's using the software easier, are you sure there is no another way that would not force the use to enter "-" for a phone number? is it how you usually write your number down or send it to someone when they ask for it? I think instead of forcing the user to use "-" in the phone number you can come up with a better design. – jimjim Sep 22 '16 at 22:58
  • 1
    Please consider international numbers too, for example +155512345678 for a number in USA. It's not as simple as checking for dashes in the right place. Let people enter their own format, perhaps check for a minimum number of digits. – DavidG Sep 22 '16 at 22:59
  • 1
    Possible duplicate of [Regex to match all us phone number formats](http://stackoverflow.com/questions/18091324/regex-to-match-all-us-phone-number-formats) – Cody Sep 22 '16 at 22:59
  • I cannot use Regex Dont worry about the number being an ACTUAL number. Just as long as it fits the xxx-xxx-xxxx format. – Xoax Sep 22 '16 at 23:17
  • Just an FYI, what you are calling major and minor are technically called exchange and subscriber or station. – Jaquez Sep 23 '16 at 01:56

3 Answers3

1
   bool wrong = true;

        while (wrong)
        {
            string phoneNumber = Console.ReadLine();
            string[] values = phoneNumber.Split('-');
            while (string.IsNullOrWhiteSpace(phoneNumber))
            {
                Console.WriteLine("Invalid - Please do not leave blank");
            }

            if (values.Length == 3 && values[0].Length == 3 && values[1].Length == 3 && values[2].Length == 4)
            {
                int yesnumber;
                List<int> intvalues = new List<int>();
                for (int number = 0; number < values.Length; number++)
                {
                    bool isNumeric = Int32.TryParse(values[number], out yesnumber);
                    if (isNumeric == true)
                    { intvalues.Add(yesnumber); }
                }
                if(intvalues.Count == 3)
                {
                    Console.WriteLine("Congratulations This is a valid number");
                    break;
                }

                else { Console.WriteLine("This is not a valid number"); }
            }

            else { Console.WriteLine("This is not a valid number"); }
        }
        Console.ReadLine();
    }

This is for a simple console application, but it works well for requiring the user to have all the things you ask for in that specific format.

Edit* I fixed the error for not checking numbers.

Raevan
  • 46
  • 5
1

Even when you aren't using a regular expression engine, it can help to use a pattern. For example, a number is valid "if it has digits in the same places as the pattern and non-digits are exactly the same" can be coded like this:

bool IsPhoneNumber(string input, string pattern)
{
     if (input.Length != pattern.Length) return false;

     for( int i = 0; i < input.Length; ++i ) {
         bool ith_character_ok;
         if (Char.IsDigit(pattern, i))
             ith_character_ok = Char.IsDigit(input, i);
         else
             ith_character_ok = (input[i] == pattern[i]);

         if (!ith_character_ok) return false;
     }
     return true;
}

Now you can even check against multiple patterns, for example

if (IsPhoneNumber(input, "000-000-0000") || IsPhoneNumber(input, "(000) 000-0000"))

But it can also be used for matching other things, for example, a pattern of 000-00-0000 for social security numbers.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1
List<string> phoneNumbers = new List<string> {"111-111-1111",
                                             "1-111-111-1111",
                                             "111111-1111",
                                             "111-1111111",
                                             "(111)111-1111",
                                             "(111) 111-1111",
                                             "11111111111",
                                             "111111-11111",
                                             "1111111111111"};

foreach(string phoneNumber in phoneNumbers)
{
    Match match = Regex.Match(phoneNumber,@"^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$", RegexOptions.IgnoreCase);

    Console.WriteLine(phoneNumber + " " + match.Success);
}


//111-111-1111   True
//1-111-111-1111 True
//111111-1111    True
//111-1111111    True
//(111)111-1111  True
//(111) 111-1111 True
//11111111111    True
//111111-11111   False
//1111111111111  True
SINGULARITY
  • 1,124
  • 11
  • 11