简体   繁体   中英

How to check phone numbers on c#?

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.

   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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM