36

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?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Dex
  • 12,527
  • 15
  • 69
  • 90
  • Does this answer your question? [How do I check whether a value in a string is an IP address](https://stackoverflow.com/questions/3634998/how-do-i-check-whether-a-value-in-a-string-is-an-ip-address) – salty Oct 31 '22 at 20:34

7 Answers7

71

Just wanted to add that instead of writing your own pattern you can use the build in one Resolv::IPv4::Regex

require 'resolv'

validates :gateway, :presence => true, :uniqueness => true,
  :format => { :with => Resolv::IPv4::Regex }
Jack
  • 1,331
  • 1
  • 12
  • 9
17

The Rails way to validate with ActiveRecord in Rails 3 is:

@ip_regex = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/

validates :gateway, 
          :presence => true, 
          :uniqueness => true,
          :format => { :with => @ip_regex } 

Good resource here: Wayback Archive - Email validation in Ruby On Rails 3 or Active model without regexp

BSMP
  • 4,596
  • 8
  • 33
  • 44
Dex
  • 12,527
  • 15
  • 69
  • 90
3

You can also just call standard's library IPAddr.new that will parse subnets, IPV6 and other cool things: (IPAddr) and return nil if the format was wrong.

Just do:

valid = !(IPAddr.new('192.168.2.0/24') rescue nil).nil?  
#=> true

valid = !(IPAddr.new('192.168.2.256') rescue nil).nil?  
#=> false
Francois
  • 1,367
  • 1
  • 15
  • 23
2

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)

validates :your_attr, ipaddr: true
yuku-t
  • 29
  • 4
0

You can also use Regexy::Web::IPv4 which can match ip addresses with port numbers too.

pragma
  • 1,290
  • 14
  • 16
0

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 :

"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"

to validate the IP Address.

I recently used it in one module so had it on desktop.

Jsinh
  • 2,539
  • 1
  • 19
  • 35
0

You should use a Regular Expression

Here is one that does what you want:

/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/.match("#{@systemIP}")
Pedro
  • 11,514
  • 5
  • 27
  • 40