简体   繁体   English

Javascript 正则表达式用于验证 IP 具有不同端口号语法的地址

[英]Javascript Regex for validate IP Address with different port number syntax

We have a React form that has input field, user suppose to enter IP address with / symbol port number我们有一个带有输入字段的 React 表单,用户假设输入带有 / 符号端口号的 IP 地址

Ex: 192.168.0.2/30例如:192.168.0.2/30

I have seen many answers related to ":" syntax but no in this syntax, Need your help to sorted this out on React project Thanks in advance我已经看到许多与“:”语法相关的答案,但在此语法中没有,需要您的帮助才能在 React 项目中解决这个问题提前谢谢

You can try the following regex expression that fits your case:您可以尝试以下适合您情况的正则表达式:

 const expression = "^(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]?)\/([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" const ip_port = "192.168.0.2/65535" const matches = ip_port.match(expression); console.log("Matches",matches[0]);

Though I would suggest if possible to have two input fields one for IP address and the second for the port number, this way you can validate each field by itself.虽然我建议如果可能有两个输入字段,一个用于 IP 地址,第二个用于端口号,这样您就可以自行验证每个字段。 This way you can use a is-ip package to validate the ip and you can use a simple regex ^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$ to valide the port number.这样,您可以使用is-ip package 来验证 ip 并且您可以使用简单的正则表达式^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$来验证端口号。

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

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