0

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

  • 1
    Parsing something what is not `int` to `int` is as wrong, as a converting `int` to `string` and checking its length to see if the number is bigger than `99`. – Sinatr Jun 08 '17 at 15:09

2 Answers2

5

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

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
2

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,}+$");
Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
RoJaIt
  • 451
  • 3
  • 10