Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Validate IP String

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?

like image 386
Dex Avatar asked Sep 20 '10 23:09

Dex


3 Answers

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 }
like image 187
Jack Avatar answered Nov 17 '22 08:11

Jack


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

like image 17
Dex Avatar answered Nov 17 '22 08:11

Dex


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
like image 3
Francois Avatar answered Nov 17 '22 08:11

Francois