简体   繁体   English

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

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

I was able to create a script to validate IP address correctly like this, 我能够创建一个脚本来像这样正确验证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;
}

The results was great but until then they made a unusual request that they require me to validate user enter 3 digits and not allow enter 1 or 2 digits like for example, user can't enter 115.42.150.37, instead must enter 115.042.150.037. 结果很棒,但是直到那时他们提出了一个不寻常的要求,要求我验证用户输入的3位数字,并且不允许输入1或2位数字,例如,用户不能输入115.42.150.37,而必须输入115.042.150.037。 How can I add verify to ensure they enter 3 digits? 如何添加验证以确保他们输入3位数字?

In your code it has [01]?[0-9][0-9] . 在您的代码中,它具有[01]?[0-9][0-9] It says it can have a leading 0 or 1 or not followed by two numbers. 它说它可以有一个前导0或1,也可以不跟两个数字。 Simple fix is to remove the ? 简单的解决方法是删除? where it makes the 0 and 1 optional 它使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])$/

You can do it by removing alls "?" 您可以通过删除所有“?”来做到这一点。 in the regex. 在正则表达式中。 This way your regex requires 3 digits every time and accepts things like 192.168.001.001 这样,您的正则表达式每次都需要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])$

I think this regex will do the job. 我认为这个正则表达式可以完成这项工作。 Hope this helps. 希望这可以帮助。

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

You can use split() and every() in conjunction to get that validation work: 您可以结合使用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