繁体   English   中英

如何验证IP地址以确保用户在四个部分中输入3位数字?

[英]How to validate IP Address to make sure user enter 3 digits in four parts?

我能够创建一个脚本来像这样正确验证IP地址,

var ipformat = /^(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]?)$/;

if(g_form.getValue('src_nw_ip_hdcc').match(ipformat)){
    return true;
}else{
    alert("You have entered an invalid Network IP Address!");
    return false;
}

结果很棒,但是直到那时他们提出了一个不寻常的要求,要求我验证用户输入的3位数字,并且不允许输入1或2位数字,例如,用户不能输入115.42.150.37,而必须输入115.042.150.037。 如何添加验证以确保他们输入3位数字?

在您的代码中,它具有[01]?[0-9][0-9] 它说它可以有一个前导0或1,也可以不跟两个数字。 简单的解决方法是删除? 它使0和1为可选

/^(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])$/

您可以通过删除所有“?”来做到这一点。 在正则表达式中。 这样,您的正则表达式每次都需要3位数字,并接受192.168.001.001之类的信息

^(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])$

我认为这个正则表达式可以完成这项工作。 希望这可以帮助。

 const regex = /^(((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))\\.){3}((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))$/g; console.log('Should match'); console.log('255.255.255.255'.match(regex)); console.log('012.000.255.001'.match(regex)); console.log('000.000.000.000'.match(regex)); console.log('Should not match'); console.log('255.255.255.'.match(regex)); console.log('255.255.255.-1'.match(regex)); console.log('.255.255.'.match(regex)); console.log('255.275.255.'.match(regex)); console.log('255.275.255.1'.match(regex)); console.log('25.5.55.1'.match(regex)); 

您可以结合使用split()every()来完成验证工作:

 function checkIp(ip) { var isCorrect = ip.split('.').every(addr => addr.length === 3); if (isCorrect) { return 'Ip address is correct'; } return 'Ip address is incorrect'; } var ip = '115.042.150.037'; console.log(checkIp(ip)); ip = '11.042.150.037'; console.log(checkIp(ip)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM