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 = "";
}
}
}
}
CodePudding user response:
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
}
CodePudding user response:
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
