简体   繁体   中英

Validating phone numbers with specific character size in C#

There is a method in my program that verifies if a phone number has 13 characters, I want to return false if there is more or less characters than 13, and return true if has 13 characters. So far, i made this, i think i got the 13 characters, anything less or more it gives me an ArgumentOutOfRangeException:

public bool CheckPhone()
        {
            int sum = 0;
            int rest;
            int i;

            for (i = 1; i <= 12; i++)
            {
                if (Phone.Substring(i - 1, i - (i - 1)).Contains("")==false)
                {
                    return false;
                }
                else
                {
                    sum += int.Parse(Phone.Substring(i - 1, i - (i - 1))) * (13 - i);
                }
            }
            rest = (sum * 11) % 12;

            if ((rest == 11) || (rest == 12))
            {
                rest = 0;
                return true;
            }
            else
            {
                return false;
            }
        }
public bool CheckPhone()
    => Phone.Length == 13 && Phone.All(Char.IsDigit);

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