Three dots in textbox

Viewed 921

I have a textbox C# for IP addressing; validating IP address. However, I'm trying to limit to numbers and the amount of dots a user can enter in for the IP address. This way it limits errors.

Seems I'm able to enter one dot, I would like to increase that number to three. I can create a "Regex.IsMatch" and validate using "IPAddress", but I'm just trying to limit what the user can enter before pressing a button to proceed.

Is there a way to do this? Searching the Internet haven't found any way to do this.

    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";
    bool CKDots = Regex.IsMatch(TracertIP, pattern);

    private void txtTracerouteIP_KeyPress(object sender, KeyPressEventArgs e)
    {
        // Enter only numbers.
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
        {
            e.Handled = true;
        }
        // Only one dot, but I need three.
        //if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        //{
        //    e.Handled = true;
        //}
    }
2 Answers

Since the MaskedTextBox is not an option and you prefer the TextBox, then maybe this would lead to something.

using System;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;

namespace SomeNamespace
{
    [DesignerCategory("Code")]
    public class IPTextBox : TextBox
    {
        #region Constructors

        public IPTextBox() : base() { }

        #endregion

        #region Public Properties

        [Browsable(false)]
        public bool IsValidIP => IsValidInput(Text, true);

        #endregion

        #region Private Methods

        private bool IsValidInput() => IsValidInput(Text);

        private bool IsValidInput(string input, bool full = false)
        {
            var split = input.Split('.');
            var parts = split.Where(x => int.TryParse(x, out _));

            return !input.StartsWith(".")
                && !input.EndsWith("..")
                && !split.Any(x => x.Length > 1 && x.StartsWith("0"))
                && (full ? parts.Count() == 4 : split.Count() < 5)
                && parts.All(x => int.Parse(x) < 256);
        }

        #endregion

        #region Base

        protected override void OnTextChanged(EventArgs e)
        {
            if (Text.Trim().Length > 0 && !IsValidInput())
            {
                SendKeys.SendWait("{BS}");
                OnInvalidInput();
            }
            else
                base.OnTextChanged(e);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {           
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != '.')
            {
                e.Handled = true;
                OnInvalidInput();
            }
            else
                base.OnKeyPress(e);
        }

        private const int WM_PASTE = 0x0302;        

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_PASTE:
                    if (!IsValidInput(Clipboard.GetText()))
                        return;
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }

        #endregion

        #region Custom Events

        public event EventHandler InvalidInput;

        protected virtual void OnInvalidInput()
        {
            var h = InvalidInput;
            h?.Invoke(this, EventArgs.Empty);
        }

        #endregion
    }
}

Steps & Description


  • Derive a new class from TextBox control.

  • Override the OnKeyPress method to permit the control, digit, and . keys only.

  • Override the OnTextChanged method to validate the modified text thru the IsValidInput function and delete the last entered character if the function returns false.

  • The IsValidInput function checks whether the entered text can produce a valid IP address or a part of it.

  • The IsValidIP read-only property returns whether the text is a valid IP address. As you know, the IPAddress.TryParse(..) will also return true if you pass for example 1 or 192.168 because it parses them as 0.0.0.1 and 192.0.0.168 respectively. So it won't help here.

  • The custom event InvalidInput is raised whenever an invalid key is pressed and if the Text does not form a valid IP address or a part of it. So, the event can be handled in the implementation to alert the user if necessary.

That's it all.

IP Address TextBox

Related


How to TextBox inputs of custom format?

We can keep it simple and use the validating event:

    this.txtTracerouteIP.Validating += this.txtTracerouteIP_Validating;

And then:

    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$";

    private void txtTracerouteIP_Validating(object sender, CancelEventArgs e)
    {
        if (!Regex.IsMatch(txtTracerouteIP.Text, pattern))
        {
            MessageBox.Show("IP Address must be in the format '255.255.255.255'!");
            txtTracerouteIP.SelectAll();
            e.Cancel = true;
        }
    }
Related