JS验证IP:端口 [英] JS Validation IP:Port

查看:442
本文介绍了JS验证IP:端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,关于如何一起验证IP:Port. 例如:

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

192.158.2.10:80<-有效

192.158.2.10:80 <--Valid

192.158.2.10< ---无效

192.158.2.10 <---Invalid

所以端口是必须的,我找到了一些IP验证(正则表达式),但是要与端口组合起来就没有运气了.我不想为端口使用单独的输入字段.

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.

我的主意是这样:

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?

推荐答案

正则表达式必须荒谬地长,以验证数字是否在可接受的范围内.相反,我会用这个:

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

演示 jsfiddle.net/eH2e5

这篇关于JS验证IP:端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆