C# 如何验证(特定于国家/地区的)电话号码

C# 如何验证(特定于国家/地区的)电话号码,c#,regex,C#,Regex,有效的电话号码包含: 少于9个字符 开头是“+” 只有数字 我正在尝试使用正则表达式,但我刚刚开始使用它们,我并不擅长。到目前为止,我掌握的代码是: static void Main(string[] args) { Console.WriteLine("Enter a phone number."); string telNo = Console.ReadLine(); if (Regex.Match(telNo, @"^(\+[0-

有效的电话号码包含:

  • 少于9个字符
  • 开头是“+”
  • 只有数字
我正在尝试使用正则表达式,但我刚刚开始使用它们,我并不擅长。到目前为止,我掌握的代码是:

static void Main(string[] args)
{
    Console.WriteLine("Enter a phone number.");
    string telNo = Console.ReadLine();

    if (Regex.Match(telNo, @"^(\+[0-9])$").Success)
        Console.WriteLine("correctly entered");

    else
        Console.WriteLine("incorrectly entered");

    Console.ReadLine();
}

但我不知道如何用这种方法检查绳子的长度。非常感谢您的帮助。

您的正则表达式应该是这样的,您需要有关字符计数器的信息

@"^(\+[0-9]{9})$"

类似这样的方法可能会奏效:

^+\d{0,9}

但是,我建议您使用正则表达式测试工具来了解正则表达式的工作原理。我自己仍然喜欢大量使用它们,因为我不经常编写正则表达式。这里有一个例子,但还有更多的例子


Jacek的正则表达式运行良好

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter a phone number.");
        string telNo = Console.ReadLine();                      
        Console.WriteLine("{0}correctly entered", IsPhoneNumber(telNo) ? "" : "in");    
        Console.ReadLine(); 
    }

    public static bool IsPhoneNumber(string number)
    {
        return Regex.Match(number, @"^(\+[0-9]{9})$").Success;
    }
}

用于有效或无效USAPhoneNumber的简单函数

   /// <summary>
    /// Allows phone number of the format: NPA = [2-9][0-8][0-9] Nxx = [2-9]      [0-9][0-9] Station = [0-9][0-9][0-9][0-9]
    /// </summary>
    /// <param name="strPhone"></param>
    /// <returns></returns>
    public static bool IsValidUSPhoneNumber(string strPhone)
    {
        string regExPattern = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";
        return MatchStringFromRegex(strPhone, regExPattern);
    }
    // Function which is used in IsValidUSPhoneNumber function
    public static bool MatchStringFromRegex(string str, string regexstr)
    {
        str = str.Trim();
        System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regexstr);
        return pattern.IsMatch(str);
    }
//
///允许以下格式的电话号码:NPA=[2-9][0-8][0-9]Nxx=[2-9][0-9][0-9]Station=[0-9][0-9][0-9][0-9]
/// 
/// 
/// 
公共静态bool IsValidUSPhoneNumber(字符串strPhone)
{
字符串regexpatern=@“^[01]?[-.]?(\([2-9]\d{2}\)|[2-9]\d{2})[-.]?\d{3}[-.]?\d{4}$”;
从regex(strPhone、regexpatern)返回匹配字符串;
}
//IsValidUSPhoneNumber函数中使用的函数
公共静态bool MatchStringFromRegex(字符串str,字符串regexstr)
{
str=str.Trim();
System.Text.RegularExpressions.Regex模式=新的System.Text.RegularExpressions.Regex(regexstr);
返回模式.IsMatch(str);
}
不要使用正则表达式

正则表达式的变量太多,无法使用。相反,只需从字符串中删除所有非0-9的字符,然后检查是否还有正确的位数。那么,用户包含或不包含的额外内容就不重要了。。。()x-+[]等等,因为它只是将它们全部去掉,只计算0-9个字符

我有一个非常好用的字符串扩展,可以支持多种格式。它接受一个
IsRequired
参数。因此,您可以像这样验证电话号码:

string phone = "(999)999-9999"
bool isValidPhone = phone.ValidatePhoneNumber(true) // returns true

string phone ="1234567890"
bool isValidPhone = phone.ValidatePhoneNumber(true) // returns true

string phone = ""
bool isValidPhone = phone.ValidatePhoneNumber(false) // not required, so returns true

string phone = ""
bool isValidPhone = phone.ValidatePhoneNumber(true) // required, so returns false

string phone ="12345"
bool isValidPhone = phone.ValidatePhoneNumber(true) // returns false

string phone ="foobar"
bool isValidPhone = phone.ValidatePhoneNumber(true) // returns false
以下是代码(假设为10位美国电话号码,请相应调整):

公共静态类StringExtensions
{
/// 
///根据美国电话号码检查电话号码是否包含10位数字。
///如果'IsRequired'为true,则空字符串将返回False。
///如果'IsRequired'为false,则空字符串将返回True。
/// 
/// 
/// 
/// 
公共静态bool ValidatePhoneNumber(此字符串电话需要bool)
{
if(string.IsNullOrEmpty(phone)和!IsRequired)
返回true;
if(string.IsNullOrEmpty(电话)和IsRequired)
返回false;
var=phone.RemoveNonNumeric();
如果(需要)
{
如果(清洁的长度==10)
返回true;
其他的
返回false;
}
其他的
{
如果(0.Length==0)
返回true;
否则,如果(已清洁。长度>0,已清洁。长度<10)
返回false;
否则,如果(已清理。长度==10)
返回true;
其他的
return false;//不应该到达这里
}
}
/// 
///从字符串中删除所有非数字字符
/// 
/// 
/// 
公共静态字符串RemoveNonNumeric(此字符串电话)
{
返回Regex.Replace(电话,@“[^0-9]+”,“”);
}
}

如果要查找特定于国家/地区的正则表达式,请尝试此表达式,它适用于所有澳大利亚(+61-)数字。我已经就如何将其用于其他用途发表了意见

public static bool IsValidPhoneNumber(string phoneNumber)
{
    //will match +61 or +61- or 0 or nothing followed by a nine digit number
    return Regex.Match(phoneNumber, 
        @"^([\+]?61[-]?|[0])?[1-9][0-9]{8}$").Success;
    //to vary this, replace 61 with an international code of your choice 
    //or remove [\+]?61[-]? if international code isn't needed
    //{8} is the number of digits in the actual phone number less one
}

此解决方案验证验证电话号码的每个测试标准,它还利用了Regex API。标准包括间距、任何非数值、区号(由您指定)、电话号码应具有的数值(位数),还包括错误消息以及电话号码旧状态和新状态

以下是源代码:

public class PhoneNumberValidator
{
    public string ErrorMessage { get; set; }
    public int PhoneNumberDigits { get; set; }
    public string CachedPhoneNumber { get; set; }

    private Dictionary<int, string> VaildAreaCodes()
    {
        return new Dictionary<int, string>
        {
            [3] = "0",
            [4] = "27"
        };
    }

    private bool IsInteger(string value)
    {
        return int.TryParse(value, out int result);
    }

    private string GetConsecutiveCharsInPhoneNumberStr(string phoneNumber)
    {
        switch (PhoneNumberDigits)
        {
            case 0:
            case 10:
                PhoneNumberDigits = 10;
                return phoneNumber.Substring(phoneNumber.Length - 7);

            case 11:
                return phoneNumber.Substring(phoneNumber.Length - 8);

            default:
                return string.Empty;
        }
    }

    private bool IsValidAreaCode(ref string phoneNumber, string areaCode)
    {
        if (!IsInteger(areaCode))
        {
            ErrorMessage = "Area code characters of Phone Number value should only contain integers.";
            return false;
        }

        var areaCodeLength = areaCode.Length;
        var invalidAreaCodeMessage = "Phone Number value contains invalid area code.";
        switch (areaCodeLength)
        {
            case 2:
                phoneNumber = string.Concat("0", phoneNumber);
                return true;

            case 3:
                if (!areaCode.StartsWith(VaildAreaCodes[3]))
                    ErrorMessage = invalidAreaCodeMessage;
                return string.IsNullOrWhiteSpace(ErrorMessage) ? true : false;

            case 4:
                if (areaCode.StartsWith(VaildAreaCodes[4]))
                {
                    phoneNumber = string.Concat("0", phoneNumber.Remove(0, 2)); // replace first two charaters with zero
                    return true;
                }                    
                ErrorMessage = invalidAreaCodeMessage;
                return false;                

            default:
                ErrorMessage = invalidAreaCodeMessage;
                return false;
        }
    }   

    public bool IsValidPhoneNumber(ref string phoneNumber)
    {
        CachedPhoneNumber = phoneNumber;

        if (string.IsNullOrWhiteSpace(phoneNumber))
        {
            ErrorMessage = "Phone Number value should not be equivalent to null.";
            return false;
        }

        phoneNumber = Regex.Replace(phoneNumber, " {2,}", string.Empty); // remove all whitespaces
        phoneNumber = Regex.Replace(phoneNumber, "[^0-9]", string.Empty); // remove all non numeric characters

        var lastConsecutiveCharsInPhoneNumberStr = GetConsecutiveCharsInPhoneNumberStr(phoneNumber);

        if (string.IsNullOrWhiteSpace(lastConsecutiveCharsInPhoneNumberStr))
        {
            ErrorMessage = "Phone Number value not supported.";
            return false;
        }

        if (!IsInteger(lastConsecutiveCharsInPhoneNumberStr))
        {
            ErrorMessage = "Last consecutive characters of Phone Number value should only contain integers.";
            return false;
        }

        var phoneNumberAreaCode = phoneNumber.Replace(lastConsecutiveCharsInPhoneNumberStr, "");

        if (!IsValidAreaCode(ref phoneNumber, phoneNumberAreaCode))
        {
            return false;
        }            

        if (phoneNumber.Length != PhoneNumberDigits)
        {
            ErrorMessage = string.Format("Phone Number value should contain {0} characters instead of {1} characters.", PhoneNumberDigits, phoneNumber.Length);
            return false;
        }

        return true;
    }
}
公共类PhoneNumberValidator
{
公共字符串错误消息{get;set;}
public int PhoneNumberDigits{get;set;}
公共字符串CachedPhoneNumber{get;set;}
专用词典
{
返回新词典
{
[3] = "0",
[4] = "27"
};
}
私有布尔IsInteger(字符串值)
{
返回int.TryParse(值,out int result);
}
私有字符串GetConcertiveCharsinPhoneNumberstr(字符串电话号码)
{
开关(PhoneNumberDigits)
{
案例0:
案例10:
PhoneNumberGits=10;
返回phoneNumber.Substring(phoneNumber.Length-7);
案例11:
返回phoneNumber.Substring(phoneNumber.Length-8);
违约:
返回字符串。空;
}
}
专用布尔IsValidAreaCode(参考字符串电话号码、字符串区号)
{
如果(!IsInteger(区域代码))
{
ErrorMessage=“电话号码值的区号字符应仅包含整数。”;
返回false;
}
var areaCodeLength=areaCode.Length;
var invalidAreaCodeMessage=“电话号码值包含无效的区号。”;
开关(区域代码长度)
{
案例2:
phoneNumber=string.Concat(“0”,phoneNumber);
返回true;
案例3:
如果(!areaCode.StartWith(VaildAreaCodes[3]))
ErrorMessage=InvalidReacodeMessage;
返回字符串.IsNullOrWhiteSpace(ErrorMessage)?true:false;
案例4:
if(区号为STARTSWITS(VaildAreaCodes[4]))
{
public class PhoneNumberValidator
{
    public string ErrorMessage { get; set; }
    public int PhoneNumberDigits { get; set; }
    public string CachedPhoneNumber { get; set; }

    private Dictionary<int, string> VaildAreaCodes()
    {
        return new Dictionary<int, string>
        {
            [3] = "0",
            [4] = "27"
        };
    }

    private bool IsInteger(string value)
    {
        return int.TryParse(value, out int result);
    }

    private string GetConsecutiveCharsInPhoneNumberStr(string phoneNumber)
    {
        switch (PhoneNumberDigits)
        {
            case 0:
            case 10:
                PhoneNumberDigits = 10;
                return phoneNumber.Substring(phoneNumber.Length - 7);

            case 11:
                return phoneNumber.Substring(phoneNumber.Length - 8);

            default:
                return string.Empty;
        }
    }

    private bool IsValidAreaCode(ref string phoneNumber, string areaCode)
    {
        if (!IsInteger(areaCode))
        {
            ErrorMessage = "Area code characters of Phone Number value should only contain integers.";
            return false;
        }

        var areaCodeLength = areaCode.Length;
        var invalidAreaCodeMessage = "Phone Number value contains invalid area code.";
        switch (areaCodeLength)
        {
            case 2:
                phoneNumber = string.Concat("0", phoneNumber);
                return true;

            case 3:
                if (!areaCode.StartsWith(VaildAreaCodes[3]))
                    ErrorMessage = invalidAreaCodeMessage;
                return string.IsNullOrWhiteSpace(ErrorMessage) ? true : false;

            case 4:
                if (areaCode.StartsWith(VaildAreaCodes[4]))
                {
                    phoneNumber = string.Concat("0", phoneNumber.Remove(0, 2)); // replace first two charaters with zero
                    return true;
                }                    
                ErrorMessage = invalidAreaCodeMessage;
                return false;                

            default:
                ErrorMessage = invalidAreaCodeMessage;
                return false;
        }
    }   

    public bool IsValidPhoneNumber(ref string phoneNumber)
    {
        CachedPhoneNumber = phoneNumber;

        if (string.IsNullOrWhiteSpace(phoneNumber))
        {
            ErrorMessage = "Phone Number value should not be equivalent to null.";
            return false;
        }

        phoneNumber = Regex.Replace(phoneNumber, " {2,}", string.Empty); // remove all whitespaces
        phoneNumber = Regex.Replace(phoneNumber, "[^0-9]", string.Empty); // remove all non numeric characters

        var lastConsecutiveCharsInPhoneNumberStr = GetConsecutiveCharsInPhoneNumberStr(phoneNumber);

        if (string.IsNullOrWhiteSpace(lastConsecutiveCharsInPhoneNumberStr))
        {
            ErrorMessage = "Phone Number value not supported.";
            return false;
        }

        if (!IsInteger(lastConsecutiveCharsInPhoneNumberStr))
        {
            ErrorMessage = "Last consecutive characters of Phone Number value should only contain integers.";
            return false;
        }

        var phoneNumberAreaCode = phoneNumber.Replace(lastConsecutiveCharsInPhoneNumberStr, "");

        if (!IsValidAreaCode(ref phoneNumber, phoneNumberAreaCode))
        {
            return false;
        }            

        if (phoneNumber.Length != PhoneNumberDigits)
        {
            ErrorMessage = string.Format("Phone Number value should contain {0} characters instead of {1} characters.", PhoneNumberDigits, phoneNumber.Length);
            return false;
        }

        return true;
    }
}
    internal static bool IsValidPhoneNumber(this string This)
    {
        var phoneNumber = This.Trim()
            .Replace(" ", "")
            .Replace("-", "")
            .Replace("(", "")
            .Replace(")", "");
        return Regex.Match(phoneNumber, @"^\+\d{5,15}$").Success;
    }