1

I have application form in C# and I have following code to validate IP address from masked text box:

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);
    }
}

In IPAdres_TypeValidationComleted function while if statement is true errorProvider1 blinks and give "INVALID IP" message else it should disappear. The problem is that input type seems to be always invalid even if I put valid IP adress.

Codor
  • 17,447
  • 9
  • 29
  • 56
ElConrado
  • 1,477
  • 4
  • 20
  • 46
  • here is one solution: [**Solution**][1] [1]: http://stackoverflow.com/questions/7924000/ip-address-in-a-maskedtextbox – DareDevil May 04 '15 at 11:29

3 Answers3

5

This could be due to regional settings and decimals. You can try this Mask and see if it solves the issue:

IPAdressBox.Mask = @"###\.###\.###\.###";
Sébastien Sevrin
  • 5,267
  • 2
  • 22
  • 39
  • Thanks! It's a good answer for my problem but in general it is not complex solution because if you type 127.0.0.1 in this case it returns address with space characters like this: 127.0__.0__.1 and for validation it's invalid. – ElConrado May 04 '15 at 16:43
2

When you set 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).

If your culture uses a comma as a separator, your MaskedTextBox.Text with input 123.123.123.123 will yield the text 123,123,123,123.

You can see this in IPAdress_TypeValidationCompleted: e.Message will contain "System.FormatException: An invalid IP address was specified.", as IP addresses generally can't contain commas.

If you alter the mask to ###\.###\.###\.###, escaping the dots, they will be interpreted literally as opposed to being the current culture's decimal separator.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
2

Mask should be:

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

in program should be added:

IPAdressBox.ResetOnSpace = false;
ElConrado
  • 1,477
  • 4
  • 20
  • 46