Skip to main content

A few useful C# phone and fax number validation methods.

using System.Text;
using System.Text.RegularExpressions;

namespace Validation
{
    public static class PhoneAndFaxNumberValidators
    {
        public static bool ValidatePhoneNumberCharacters(string phoneNumber)
        {
            return new Regex("^([0-9pP\\.\\s\\-\\(\\)\\#]{3,24})$").Match(phoneNumber).Success;
        }

        public static bool ValidateAreaCode(string areaCode)
        {
            return new Regex("^[0-9]{3}$").Match(areaCode).Success;
        }

        public static bool ValidateDialingPrefix(string phoneNumber)
        {
            return new Regex("^[dD]?[0-9pP]*$").Match(phoneNumber).Success;
        }

        public static bool ValidateFaxNumber(string faxNumber)
        {
            return new Regex("^([0-9pP\\.\\s\\-\\(\\)\\#]{3,24})$").Match(faxNumber).Success;
        }

        public static bool ValidateDigitMask(string digitMask)
        {
            return new Regex("^[dDxX]+$").Match(digitMask).Success;
        }

        public static string FilterDidNumber(string number)
        {
            var stringBuilder = new StringBuilder();

            foreach (var c in number)
            {
                if (char.IsDigit(c))
                    stringBuilder.Append(c);
            }

            return stringBuilder.ToString();
        }

        public static string CreateDialableFaxNumber(string faxNumber)
        {
            return new Regex("[^0-9A-Da-dpP#,!WwPpTt@$?;]").Replace(faxNumber, string.Empty);
        }
    }
}