简体   繁体   中英

Issue with Validating Phone number on user input,Int to large c#

Overview of Project:

I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail() . My Issue comes when using the isNumber() Function.

public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers

I suggest that you use a regular expresion to validate the input in your case

public static bool numValidation(string strNum)
{

    Regex regex = new Regex(@"^[0-9]+$");

    return (regex.IsMatch(strNum)) ;
}

Parsing a string and not using that value is not really needed.

For more details checkout this answers - Regex for numbers only

From Mauricio Gracia Gutierrez answer

I suggest that you use a regular expresion to validate the input in your case

public static bool numValidation(string strNum) {

 Regex regex = new Regex(@"^[0-9]+$"); return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed. 

For more details checkout this answers - Regex for numbers only

You could enhance the expression to check the length of the number:

Between 5 and 10 digits:

Regex regex = new Regex(@"^[\d]{5,10}+$");

Max 10 digits:

Regex regex = new Regex(@"^[\d]{10}+$");

At least 5 digits:

Regex regex = new Regex(@"^[\d]{5,}+$");

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