简体   繁体   English

在 C# 中验证 IP

[英]Validating IP in C#

I was given a project to make a basic C# IPv4 address program on Windows Forms application.我得到了一个在 Windows 窗体应用程序上制作基本 C# IPv4 地址程序的项目。 We are to have 5 text boxes (4 for each octet, one multiline textbox under for displaying the IP and class).我们将有 5 个文本框(每个八位字节 4 个,下面有一个多行文本框用于显示 IP 和类)。 In order to display the IP in the multiline textbox, I would need to first validate the numbers in all 4 textboxes (meaning all mumbers must be >= 0 and <= 255) I know there is a IPAddress.TryParse code you can use, but I am not sure how I can apply it to the 4 textboxes.为了在多行文本框中显示 IP,我需要首先验证所有 4 个文本框中的数字(意味着所有数字必须 >= 0 和 <= 255)我知道有一个 IPAddress.TryParse 代码可以使用,但我不确定如何将其应用于 4 个文本框。 Help would be very much appreciated!非常感谢您的帮助! :) :)

表格展示

In your question you write "WPF" but your screenshot is clearly a Windows Forms application so I will provide an answer for Windows Forms.在您的问题中,您写了“WPF”,但您的屏幕截图显然是 Windows 窗体应用程序,因此我将为 Windows 窗体提供答案。 However, it can easily be modified to work with WPF.但是,它可以很容易地修改为与 WPF 一起使用。

While you can validate each text box individually the interesting part of your question is how validation can be done across multiple controls.虽然您可以单独验证每个文本框,但问题的有趣部分是如何跨多个控件进行验证。 When doing validation you have to decide how the app should behave when the input is both invalid and valid.在进行验证时,您必须决定当输入既无效又有效时应用程序的行为方式。 A simple and good way is to update the visual state based on the validity of the input.一个简单而好的方法是根据输入的有效性更新视觉状态。 Eg, a button can only be clicked when the entire input is valid.例如,只有在整个输入有效时才能单击按钮。 This avoids the situation where the input is invalid, the user clicks the button and then gets an error that has to be dismissed.这避免了输入无效的情况,用户单击按钮然后收到必须解除的错误。 To further refine this you can provide hints in the UI about why something isn't valid.为了进一步完善这一点,您可以在 UI 中提供有关某些内容无效的提示。

Based on your screenshot my guess is that you want to provide some information about the result of the validation in the large text box.根据您的屏幕截图,我猜测您希望在大文本框中提供有关验证结果的一些信息。 You can create method to update the contents of this text box based on the contents of the other text boxes.您可以根据其他文本框的内容创建方法来更新此文本框的内容。 Instead of updating the large text box this method could also enable and disable buttons etc. for a more realistic scenario.除了更新大文本框,此方法还可以启用和禁用按钮等,以实现更真实的场景。

private void UpdateVisualState()
{
    var ipString = $"{textBox1.Text}.{textBox2.Text}.{textBox3.Text}.{textBox4.Text}";
    infoTextBox.Text = IPAddress.TryParse(ipString, out var address)
        ? address.ToString()
        : "(Invalid IP address)";
}

This method will take the text in textBox1 to textBox4 , create an IP address from this, parse this IP address and update infoTextBox with either the parsed IP address or a text that indicates that the IP address is invalid.此方法将textBox1的文本带到textBox4textBox4创建一个 IP 地址,解析此 IP 地址并使用解析的 IP 地址或指示 IP 地址无效的文本更新infoTextBox

Now all you have to do is to call this method every time the text in each of the IP address octet text boxes change:现在您要做的就是在每次 IP 地址八位字节文本框中的文本更改时调用此方法:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    UpdateVisualState();
}

Do the same for the remaining three text boxes with IP address octets.对其余三个带有 IP 地址八位字节的文本框执行相同操作。

This a very simple way to validate the entire state of a form and as your user interface and validation rules become more complex you may find that it doesn't scale so well.这是验证表单整个状态的一种非常简单的方法,随着您的用户界面和验证规则变得越来越复杂,您可能会发现它不能很好地扩展。 However, to get started this if fine.但是,如果可以的话,就开始吧。

To learn about more advanced ways to do validation you can read User Input Validation in Windows Forms .要了解更高级的验证方法,您可以阅读Windows 窗体中的用户输入验证

You can use LostFocus .您可以使用LostFocus Attach TextBox_KeyDown to all of your texboxes which you want to make validationTextBox_KeyDown附加到要进行验证的所有文本框

private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    var textbox = (TextBox)sender;
    var isNumber = int.TryParse(textbox.Text, out var num);
    if (!isNumber)
    {
        //not validated
        return; 
    }

    if (!(num > 0 && num < 256)) 
    {
       //not validated
       return;
    }

    //valid 
}

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // call the LostFocus event to validate the TextBox
        ((TextBox)sender).RaiseEvent(new RoutedEventArgs(TextBox.LostFocusEvent));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM