Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...