Skip to content Skip to sidebar Skip to footer

Js Validation Ip:port

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 found some IP validation(Regex) b

Solution 1:

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:

functionvalidateIpAndPort(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);
        });
}

functionvalidateNum(input, min, max) {
    var num = +input;
    return num >= min && num <= max && input === num.toString();
}

Demo jsfiddle.net/eH2e5

Solution 2:

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})$/

Solution 3:

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

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

Solution 4:

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

Solution 5:

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

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">functionValidateIPaddress(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>

Post a Comment for "Js Validation Ip:port"