JS Validation IP:Port

前端 未结 5 1005
既然无缘
既然无缘 2020-12-06 22:09

I have a question, on how to validate IP:Port together. example:

192.158.2.10:80 <--Valid

192.158.2.10 <---Invalid

So the port is a must, I fo

5条回答
  •  借酒劲吻你
    2020-12-06 22:28

    A regular expression would have to be ridiculously long in order to validate that the numbers fall within the acceptable range. Instead, I'd use this:

    function validateIpAndPort(input) {
        var parts = input.split(":");
        var ip = parts[0].split(".");
        var port = parts[1];
        return validateNum(port, 1, 65535) &&
            ip.length == 4 &&
            ip.every(function (segment) {
                return validateNum(segment, 0, 255);
            });
    }
    
    function validateNum(input, min, max) {
        var num = +input;
        return num >= min && num <= max && input === num.toString();
    }
    

    Demo jsfiddle.net/eH2e5

提交回复
热议问题