IP Address in a MaskedTextBox?

前端 未结 6 1531
無奈伤痛
無奈伤痛 2020-12-03 15:09

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).

6条回答
  •  爱一瞬间的悲伤
    2020-12-03 15:40

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

提交回复
热议问题