2015-04-30 66 views
10

有效電話號碼包含:如何驗證電話號碼

少於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(); 
} 

但我不知道如何檢查字符串的長度這種方式。任何幫助表示讚賞。

+3

[電話號碼驗證的綜合正則表達式]的可能重複(http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – sab669

+2

你想在你的正則表達式中使用服務器代碼(C#)或在Java腳本?我不確定,但可能會有小差異 – Jacek

+0

感謝大家的幫助,最後爲我工作的那個人是@「^(\ + \ d [0-9] {1,8})$」 –

回答

11

亞切克的正則表達式工作正常

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; 
    } 
} 
14

你的正則表達式應該是這樣的,您需要了解字符計數器信息

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

它說錯誤地輸入每個場景 –

+2

@Adam Higgins在https://regex101.com/找到更多的幫助。這個正則表達式看起來不錯 – Jacek

+1

C#正則表達式在那個網站上的設置是什麼?我只看到PHP,Javascript和Python。 – krillgar

2

像這樣的東西可以工作:

^+ \ d {0,9}

但我會建議與正則表達式測試者一起玩,以更多地瞭解正則表達式的工作原理。我仍然喜歡自己使用它們,因爲我經常不寫正則表達式。這裏有一個例子,但還有更多。

https://regex101.com/

1

爲有效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); 
    } 
0

不使用正則表達式!

正則表達式有太多變量可用於任何用途。相反,只要刪除字符串中不是0-9的所有字符,然後檢查是否有剩餘的數字。然後,無論用戶包含什麼額外的東西或不包括...()x - + []等等,因爲它只是將它們全部剝離並且只計數字符0-9。

我有一個很好的字符串擴展,並允許多種格式。它接受IsRequired參數。所以,你可以驗證這樣一個電話號碼:(假定一個10位數的美國電話號碼相應的調整)

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 

下面的代碼:

public static class StringExtensions 
{ 

    /// <summary> 
    /// Checks to be sure a phone number contains 10 digits as per American phone numbers. 
    /// If 'IsRequired' is true, then an empty string will return False. 
    /// If 'IsRequired' is false, then an empty string will return True. 
    /// </summary> 
    /// <param name="phone"></param> 
    /// <param name="IsRequired"></param> 
    /// <returns></returns> 
    public static bool ValidatePhoneNumber(this string phone, bool IsRequired) 
    { 
     if (string.IsNullOrEmpty(phone) & !IsRequired) 
      return true; 

     if (string.IsNullOrEmpty(phone) & IsRequired) 
      return false; 

     var cleaned = phone.RemoveNonNumeric(); 
     if (IsRequired) 
     { 
      if (cleaned.Length == 10) 
       return true; 
      else 
       return false; 
     } 
     else 
     { 
      if (cleaned.Length == 0) 
       return true; 
      else if (cleaned.Length > 0 & cleaned.Length < 10) 
       return false; 
      else if (cleaned.Length == 10) 
       return true; 
      else 
       return false; // should never get here 
     } 
    } 

    /// <summary> 
    /// Removes all non numeric characters from a string 
    /// </summary> 
    /// <param name="phone"></param> 
    /// <returns></returns> 
    public static string RemoveNonNumeric(this string phone) 
    { 
     return Regex.Replace(phone, @"[^0-9]+", ""); 
    } 
} 
0

如果你正在尋找一個國傢俱體的正則表達式,試試這個表達式適用於所有澳大利亞(+ 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 
} 
0

該解決方案驗證每個測試標準以驗證電話號碼,它也利用正則表達式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; 
    } 
} 

的解決方案是高度可配置的,並且可被用於任何數字的電話號碼以及區號。