maskedTextBox C# 中的 IP 地址验证

IP Address validation in maskedTextBox C#

我有 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 地址。

这可能是由于区域设置和小数点造成的。 你可以试试这个面具,看看它是否能解决问题:

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

当你设置MaskedTextBox.ValidatingType to a type, this type's Parse(string) method will be called with the MaskedTextBox's text, in this case IPAddress.Parse(string).

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

您可以在 IPAdress_TypeValidationCompleted 中看到:e.Message 将包含 "System.FormatException: An invalid IP address was specified.",因为 IP 地址通常不能包含逗号。

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

掩码应该是:

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

在程序中应添加:

IPAdressBox.ResetOnSpace = false;