Rails 3:验证 IP 字符串
在 Rails 3 中,是否有内置方法来查看字符串是否是有效的 IP 地址?
如果没有,最简单的验证方法是什么?
In Rails 3, is there a built in method for seeing if a string is a valid IP address?
If not, what is the easiest way to validate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只是想补充一点,您可以使用一个
Resolv::AddressRegex
中的构建来匹配 IPv4 和 IPv6 地址,而不是编写自己的模式。如果您只需要一个版本,可以使用
Resolv::IPv4::Regex
或Resolv::IPv6::Regex
。Just wanted to add that instead of writing your own pattern you can use the build in one
Resolv::AddressRegex
Resolv::AddressRegex
matches both IPv4 and IPv6 addresses. If you need only one version you can useResolv::IPv4::Regex
orResolv::IPv6::Regex
.Rails 3 中使用 ActiveRecord 进行验证的 Rails 方法是:
这里有很好的资源:Wayback Archive - Ruby On Rails 3 或不带 regexp 的活动模型中的电子邮件验证
The Rails way to validate with ActiveRecord in Rails 3 is:
Good resource here: Wayback Archive - Email validation in Ruby On Rails 3 or Active model without regexp
您还可以调用标准库
IPAddr.new
来解析子网、IPV6 和其他很酷的东西:(IPAddr) 并返回nil
如果格式错了。只要这样做:
You can also just call standard's library
IPAddr.new
that will parse subnets, IPV6 and other cool things: (IPAddr) and returnnil
if the format was wrong.Just do:
如果您不需要接受子网,您可以使用
Resolv::IPv4::Regex
,如下 Jack 提到的。如果您需要接受它, activemodel-ipaddr_validator gem 可能会帮助您。 (免责声明:我是宝石的作者)
You can use
Resolv::IPv4::Regex
as Jack mentioned below if you don't need to accept subnets.If you need to accept it, activemodel-ipaddr_validator gem may help you. (disclaimer: I'm the author of the gem)
我不太了解 RoR,但如果您没有找到任何内置的 IP 地址验证方法。
尝试使用这个正则表达式:
来验证 IP 地址。
我最近在一个模块中使用了它,所以将它放在桌面上。
i dont know about RoR a lot, but if you dont find any built in method for validation of IP Address.
Try on this regular expression :
to validate the IP Address.
I recently used it in one module so had it on desktop.
您应该使用
正则表达式
这是一个可以完成您想要的操作的表达式:
You should use a
Regular Expression
Here is one that does what you want:
您还可以使用 Regexy::Web::IPv4 它可以将 IP 地址与端口号匹配也。
You can also use Regexy::Web::IPv4 which can match ip addresses with port numbers too.