14

How can I use a MaskedTextBox to prevent the user from entering an invalid IP address? (I want it to behave just like the Windows one).

Brian Willis
  • 22,768
  • 9
  • 46
  • 50
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
  • Why not just read the value in and save the user some trouble? Never make a user do what you can do for them. – Woot4Moo Oct 28 '11 at 01:00

6 Answers6

24

Much simpler than the other answers:

Use System.Net.IPAddress and System.Windows.Forms.MaskedTextBox

set the following properties of the MaskedTextBox:

MaskedTextBox.Mask = ###.###.###.###
MaskedTextBox.ValidatingType = typeof(System.Net.IPAddress);

whenever the text box is validating, event MaskedTextBox.TypeValidationCompleted is raised. The event arguments show the following:

  • Is the typed text acceptable as an IP address? (= does System.Net.IPAddress.TryParse return ok)
  • Description of the error as a string
  • The parsed value (= an object of System.NET.IpAddress
  • The type of the parsed value. Needed if you have several MaskedTextBoxes with different masks

Upon receipt of this event you can decide whether to use the value or notify the user what is wrong with the value.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • 3
    Does NOT work.Only works for 123.123.123.123 - ie ALL characters present. IP address of "123.4.5.6" will appear as "123.456.." – Muckers Mate Feb 05 '16 at 14:00
  • Subscribe to event KeyDown and react the way you want to be the input if the operator presses a dot / semicolon / comma / right arrow / tab etc. – Harald Coppoolse Feb 08 '16 at 10:00
  • Also the . should probably be an escaped literal... "\." – cb88 Sep 16 '19 at 14:26
  • cb88: if you type it as a string, it should be escaped. However, in the visual studio designer properties you don't escape these characters, the input is as text in a text box, the software will escape it for you – Harald Coppoolse Sep 17 '19 at 08:31
19

Try this:

IPAddress ipAddress;
if (IPAddress.TryParse(maskedTextBoxY.Text, out ipAddress))
{
    //valid ip
 }
else
 {
    //is not valid ip
}

note: to use it, you need import the System.Net namespace:

using System.Net;
Kakashi
  • 2,165
  • 14
  • 19
5

It is better to use REGEX to validate user input. Here's an example:

         string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";

        string ip1 = "192.168.0.1";
        string ip2 = "302.0.0.1";

        Regex.IsMatch(ip1, pattern); // returns true
        Regex.IsMatch(ip2, pattern); // returns false
Dan
  • 304
  • 1
  • 4
  • Um, since when? This doesn't answer the question at all. -1 – Ry- Oct 28 '11 at 00:54
  • 1
    @minitech - I believe Woot4Moo is referring to that old saw about regexes - see http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html – Will Chesterfield Oct 28 '11 at 00:58
  • @WillChesterfield: I was referring to Dan's post, not Woot4Moo's comment. `System.Net.IPAddress.TryParse` is far better. – Ry- Oct 28 '11 at 01:32
2

Set the mask to: ###.###.###.###

Will display like this:

enter image description here

Icarus
  • 63,293
  • 14
  • 100
  • 115
  • @Woot4Moo I don't think can be done with a single mask. You'll need to listen for key pressed and handle wich characters are/aren't allowed – Icarus Oct 28 '11 at 01:04
  • Correct, MaskedTextBox does not allow you to do complex validations directly. You can use KeyPress event to read user input and determine in it is valid. And a right Regex expression does help to do this task. – Dan Oct 28 '11 at 01:07
1

There is no complex solution for this question yet. I think @HaraldDutch answer is closest, but it is not prevet from input with space character. Using additional instruction:

IPAdressBox.ResetOnSpace = false;

generaly solved problem, but more complex is to implement own custom data typewith Parse method.

            public class IPValidator
            {
                public static IPValidator Parse(string input)
                {
                    Regex regexpr = new Regex(@" ");
                    Match match = regexpr.Match(input);
                    if (match.Success)
                        return new IPValidator();
                    else throw new ArgumentException(input);
                }
            }

Where regexpr is specific expresion to validate IP. After that it can be use as ValidatingType:

 IPAdressBox.ValidatingType = typeof(IPValidator);
ElConrado
  • 1,477
  • 4
  • 20
  • 46
1

I made an IP masked textbox that mimicks the Windows one.

Has the same width, height, prevents users from entering >255 values, jumps boxes, etc, etc... If you still need it and want to try it out it's here:

https://github.com/RuvenSalamon/IP-MaskedTextBox

(I don't know if this counts as self promotion but it's open-source so I reckon it's ok.)

RuvenS
  • 109
  • 7