2015-05-04 140 views
1

我在C#应用程序的形式和我有以下代码从掩码文本框验证IP地址: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闪烁,并给予“无效IP“消息,否则它应该消失。问题是,即使我输入了有效的IP地址,输入类型似乎总是无效的。

+0

这里是一个解决方案: [** **解决方案] [1] [1]:http://stackoverflow.com/questions/7924000/ip-address-in-a-maskedtextbox – DareDevil

回答

5

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

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

谢谢!对于我的问题来说这是一个很好的答案,但总的来说,这并不是复杂的解决方案,因为如果在这种情况下键入127.0.0.1,它将返回带有如下空格字符的地址:127.0 __。0 __。1,验证它是无效的。 – ElConrado

2

当您设置MaskedTextBox.ValidatingType一种类型,这种类型的Parse(string)方法将与MaskedTextBox的文字叫,在这种情况下IPAddress.Parse(string)

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

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

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

2

面膜应该是:

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

在程序应添加:

IPAdressBox.ResetOnSpace = false;