【问题标题】:IP Address validation in maskedTextBox C#maskedTextBox C#中的IP地址验证
【发布时间】:2015-05-04 11:23:40
【问题描述】:

我有 C# 中的申请表,我有以下代码来验证屏蔽文本框中的 IP 地址:

private void MainForm_Load(object sender, EventArgs e)
{
    IPAdressBox.Mask = "###.###.###.###";
    IPAdressBox.ValidatingType = typeof(System.Net.IPAddress);
    IPAdressBox.TypeValidationCompleted += new TypeValidationEventHandler(IPAdress_TypeValidationCompleted);
}
void IPAdress_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
    if(!e.IsValidInput)
    {
        errorProvider1.SetError(this.IPAdressBox,"INVALID IP!");             
    }
    else
    {
        errorProvider1.SetError(this.IPAdressBox, String.Empty);
    }
}

在 IPAdres_TypeValidationComleted 函数中,如果语句为真,errorProvider1 会闪烁并给出“INVALID IP”消息,否则它应该会消失。问题是输入类型似乎总是无效,即使我输入了有效的 IP 地址。

【问题讨论】:

标签: c# ip-address


【解决方案1】:

这可能与区域设置和小数有关。 你可以试试这个面具,看看它是否能解决问题:

IPAdressBox.Mask = @"###\.###\.###\.###";

【讨论】:

  • 谢谢!这是我的问题的一个很好的答案,但一般来说它不是复杂的解决方案,因为如果你在这种情况下输入 127.0.0.1 它会返回带有空格字符的地址,如下所示:127.0__.0__.1 并且对于验证它是无效的。
【解决方案2】:

当您将MaskedTextBox.ValidatingType 设置为一个类型时,该类型的Parse(string) 方法将使用MaskedTextBox 的文本调用,在本例中为IPAddress.Parse(string)

如果您的文化使用逗号作为分隔符,您的 MaskedTextBox.Text 和输入 123.123.123.123 将生成文本 123,123,123,123

您可以在IPAdress_TypeValidationCompleted 中看到这一点:e.Message 将包含 “System.FormatException:指定了无效的 IP 地址。”,因为 IP 地址通常不能包含逗号。 p>

如果您将掩码更改为###\.###\.###\.###,转义点,它们将是interpreted literally as opposed to being the current culture's decimal separator

【讨论】:

    【解决方案3】:

    面具应该是:

    IPAdressBox.Mask = @"000\.000\.000\.000"; 
    

    应在程序中添加:

    IPAdressBox.ResetOnSpace = false;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      相关资源
      最近更新 更多