Rails 3: Validate IP String

12,262

Solution 1

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

Solution 2

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 }

Solution 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

Solution 4

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
Share:
12,262
Dex
Author by

Dex

Updated on June 07, 2022

Comments

  • Dex
    Dex almost 2 years

    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?

  • Dex
    Dex over 11 years
    Not sure when they added this feature, but this is so much easier
  • WarmWaffles
    WarmWaffles over 11 years
    Yes this is considerably easier. @Dex it's been around since at least ruby 1.9.2
  • davetapley
    davetapley over 11 years
    I can confirm it's in Ruby 1.8.7
  • wingfire
    wingfire about 11 years
    This is a very nice and clean solution. Works fine with Ruby 1.9.3 and Rails 3.2
  • Matt Huggins
    Matt Huggins about 9 years
    Just want to note here that there's also the Resolv::AddressRegex expression, which permits both IPv4 & IPv6 addresses.
  • Shadwell
    Shadwell about 7 years
    Works well. Maybe worth adding the disclaimer that it is your gem.
  • Lerk
    Lerk about 2 years
    Way better solution than the accepted answer with the regex.