JS Validation IP:Port

前端 未结 5 991
既然无缘
既然无缘 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:15

    You can simply use the Regex below to validate IP:Port only

    Valid IP Address (0.0.0.0 - 255.255.255.255): Valid port (1-65535)

    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):(6553[0-5]|655[0-2][0-9]|65[0-4][0-9][0-9]|6[0-4][0-9][0-9][0-9][0-9]|[1-5](\d){4}|[1-9](\d){0,3})$/

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-06 22:30

    I think '[0-9]+.[0-9]+.[0-9]+.[0-9]+:[0-9]+' might work as well

    You can test it at http://regex101.com/

    0 讨论(0)
  • 2020-12-06 22:38

    This method explained here uses a regular expression that is more complete:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    function ValidateIPaddress(ipaddress)   
        {  
         if (/^(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]?)$/.test(myForm.emailAddr.value))  
          {  
            return (true)  
          }  
        alert("You have entered an invalid IP address!")  
        return (false)  
        }
    </script>

    0 讨论(0)
  • 2020-12-06 22:41

    Perhaps this might work. It did in my preliminary tests

    var id = '192.158.2.10:80'; // passes - true
    // var id = '192.158.2.10'; // fails - false
    
    /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}\:[0-9]{1,3}$/.test(id);
    
    0 讨论(0)
提交回复
热议问题