Text box only allow IP address in windows application

╄→гoц情女王★ 提交于 2019-12-19 11:36:08

问题


I need a textbox that only allows an IP address. I can create this in a web application but i can't do this in windows application. Please help me to do this..


回答1:


Use this method to validate IP

 public bool IsValidIP(string addr)
    {
        //create our match pattern
        string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
        //create our Regular Expression object
        Regex check = new Regex(pattern);
        //boolean variable to hold the status
        bool valid = false;
        //check to make sure an ip address was provided
        if (addr == "")
        {
            //no address provided so return false
            valid = false;
        }
        else
        {
            //address provided so use the IsMatch Method
            //of the Regular Expression object
            valid = check.IsMatch(addr, 0);
        }
        //return the results
        return valid;
    }



回答2:


You could use an ASP.NET Regular Expression Validator:

<asp:RegularExpressionValidator ID="regexpName" runat="server"     
                                ErrorMessage="This expression does not validate." 
                                ControlToValidate="yourTextBox"     
                                ValidationExpression="RegEx here" />

Then set the ValidationExpression to: (Only allow IP Addresses)

\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]?)\



回答3:


Here. Take the text, split by dots, if you end up with 4 bytes (as in, 0-255 ranged numbers) it's a valid ip.

bool IsTextAValidIPAddress(string text)
{
    bool result = true;
    string[] values = text.Split(new[] { "." }, StringSplitOptions.None); //keep empty strings when splitting
    result &= values.Length == 4; // aka string has to be like "xx.xx.xx.xx"
    if(result)
        for (int i = 0; i < 4; i++) 
            result &= byte.TryParse(values[i], out temp); //each "xx" must be a byte (0-255)
    return result;
}

Or, if you can/want to leverage System.Net

bool IsTextAValidIPAddress(string text)
{
    System.Net.IPAddress test;
    return System.Net.IPAddress.TryParse(text,out test);
}


来源:https://stackoverflow.com/questions/10927523/text-box-only-allow-ip-address-in-windows-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!