Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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) but to be combind with port no luck. I dont want to use a seperate input field for port.

My Idea was to like so:

var str = '192.168.10.2:80';
var substr = ':';
     if (str.indexOf(substr) !== -1){
         var pieces = str.split(':', 2);
         var ip    = pieces[0];
         var port  = pieces[1];
         //and here validate ip and port
     }else{
         console.log('the char '+substr+' is not there');
     }

Is this right way? or there more simple?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
135 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...