0

I need to check user input values in textBox,like this [127.0.0.1]、[255.255.255.128].

The input value is between 1~255, but now have a problem when typing ".", the numbers & dot it's required.

I try to use if condition when input dot, but if continue input dot will go wrong. How should I do?

private void Check_Number(object sender, EventArgs e)
        {
            int intNumber = 0;
            TextBox tempBox = sender as TextBox;
            if (tempBox.Text != "")
            {
                if (tempBox.Text == ".") return;
                intNumber = int.Parse(tempBox.Text);
                if (intNumber >= 1 && intNumber <= 255)
                {
                    return;
                }
                else
                {
                    MessageBox.Show("Over the Upper Limit", "Error");
                    tempBox.Text = "";
                }
            }
            }
        }
Rain
  • 105
  • 1
  • 2
  • 7

2 Answers2

4

You can use IPAddress Method as following:

IPAddress IP;
var isIPAddress = IPAddress.TryParse("127.0.0.1",out IP);

if(isIPAddress)
{
    //your logic
}
else
{
    //your logic
}
1

You can split tempBox.Text by . as a delimitor and then you can compare each value is within a range or not,

var isValidIPAddress = tempBox.Text.Split('.')  //Split by '.'
          .Select(Int32.Parse) //Convert it to integer
          .All(intNumber => intNumber >= 1 && intNumber <= 255); //Check each int number is within given range

if(isValidIPAddress)
    Console.WriteLine($"{tempBox.Text} is Valid IP address");
else
    Console.WriteLine($"{tempBox.Text} is Not a Valid IP address");

Try Online: .net Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • Thank offer your method, and this method is close to what I need. – Rain Jan 05 '22 at 07:01
  • And var isValidIPAddress is boolean? I can't use it in Visual C# winform. – Rain Jan 05 '22 at 07:03
  • 1
    yes `isValidIPAddress` is boolean, You can use it in C# winform. Any reason for `I can't use it in Visual C# winform.` this statement? – Prasad Telkikar Jan 05 '22 at 07:04
  • 1
    First, Split(".") can't from 'string' to 'char', Second, All(intNumber =>), this intNumber can't declare do local variable or parameter, because this name has been used local variable range – Rain Jan 05 '22 at 07:11
  • 1
    `Split(".") can't from 'string' to 'char'` can you please tell me more on it. Regarding `All(intNumber =>)` Now you need not to define `int intNumber = 0;` at top level. – Prasad Telkikar Jan 05 '22 at 07:22
  • 1
    I change Split(".") to Split('.') , and can work – Rain Jan 05 '22 at 07:31
  • 1
    I updated my answer too. Thanks for fixing issue from my answer. – Prasad Telkikar Jan 05 '22 at 07:34