简体   繁体   English

如何在C#上检查电话号码?

[英]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. 我看过如何在C#和其他代码中将字符串格式化为电话号码 ,但是我仍然不确定。

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. 我需要做的是确保用户输入一个有效的数字,意思是1)只能是数字2)破折号必须在正确的位置,并且3)其正确的字符数。

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: 第1个应该只是一个TryParse验证。.我主要是在弄清楚第2个。

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. 现在,显示.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 因此,最终结果将是请输入数字:123-456-7890恭喜,此数字有效

or 要么

Please enter number: 123-45-45-4 This number is not valid. 请输入数字:123-45-45-4这个数字无效。

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. 但是它也可以用于匹配其他内容,例如,社会保险号码的格式为000-00-0000

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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