文本框中的三个点 [英] Three dots in textbox

查看:75
本文介绍了文本框中的三个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于IP寻址的C#文本框;验证IP地址.但是,我试图限制用户可以输入IP地址的数量和点数.这样可以减少错误.

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.

似乎我可以输入一个点,我想将该数字增加到三个.我可以创建一个"Regex.IsMatch"并使用"IPAddress"进行验证,但是我只是想限制用户在按按钮进行操作之前可以输入的内容.

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

推荐答案

由于 MaskedTextBox 不是一个选项,而您更喜欢 TextBox ,那么这可能会导致东西.

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

步骤和步骤说明


  • TextBox 控件派生新类.

    重写 OnKeyPress 方法以仅允许使用控制键,数字键和.键.

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

    重写 OnTextChanged 方法以通过 IsValidInput 函数验证修改后的文本,如果该函数返回 false .

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

    IsValidInput 函数检查输入的文本是否可以产生有效的IP地址或其一部分.

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

    IsValidIP 只读属性返回文本是否为有效的IP地址.如您所知,如果您传递了例如 1 192.168 ,则 IPAddress.TryParse(..)也将返回 true .code>,因为它将它们分别解析为 0.0.0.1 192.0.0.168 .因此,这里无济于事.

    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.

    每当按下无效键并且 Text 不构成有效IP地址或其一部分时,都会引发自定义事件 InvalidInput .因此,可以在实现中处理该事件,以在必要时向用户发出警报.

    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.

    仅此而已.

    相关


    如何自定义格式的文本框输入?

    这篇关于文本框中的三个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆