whatdoyouNeedFromMe
whatdoyouNeedFromMe

Reputation: 105

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

Upvotes: 0

Views: 70

Answers (2)

RoJaIt
RoJaIt

Reputation: 461

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,}+$");

Upvotes: 2

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10844

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

Upvotes: 5

Related Questions