Rails 3: Validate IP String - ruby-on-rails

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?

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 }

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

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

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

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.

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}")

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

Related

rails validate in model that value is inside array[2]

This question similar with this one, but those answers don't work for me(May be they are deprecated). I don't want to reopen old question by bounty, because I have a little different arguments. In my case i have an array like this
allowed_values = [99.50..200] and I tried with:
class Thing < ActiveRecord::Base
validates :price, :inclusion=> { :in => allowed_values }
It does not work. I have tried with so many ways by examples validation here. I have little experience on coding rails. So please, help to find solution.
More info:
ruby version: ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]
rails version: Rails 4.1.5
The problem must be with the way you pass the allowed_values array.
You can go with this:
validates :price, inclusion: { in: (99.50..200) }
Or, with a constant:
ALLOWED_VALUES = (99.50..200).freeze
validates :price, inclusion: { in: ALLOWED_VALUES }
[99.50..200] is an array that contains a single element: the range (99.50..200).
You are testing whether the value is in the list of objects in the array, but what you probably want is to test whether it is in the range.
So define:
allowed_values = (99.50..200)
instead of:
allowed_values = [99.50..200]
I have found a solution: How to implement min/max validator in Rails 3?
validates :price, :inclusion=> { :in => allowed_values }
does not work, it seems, validation style was changed after 3 version of rails. And I tried with:
validates_inclusion_of :number, :in => min_price..max_price
This solution has no valid case if min_price=10.5 and max_price=11
My solution is:
validates :price, :numericality => { :greater_than_or_equal_to => min_price, :less_than_or_equal_to => :max_price }
I don't know ruby(and rails) deeply and I am not right some cases. but this solution is working

Validate User email to match one of two regex's?

In my Rails app college students with either #berkeley.edu or #uw.edu email addresses can register. I have the regex for validating both ready but since I need to check the email address the user enters to see which one it matches I think I need to create one regex, but I don't know how. Here are my two regex's:
berkeley_regex = /\A[\w+\-.]+#berkeley\.edu\z/i
uw_regex = /\A[\w+\-.]+#uw\.edu\z/i
And my validate:
validates :email, :presence => true, :uniqueness => true, :format => {:with => berkeley_regex}
Now, what would the regex to check against both but only match against one look like?
Can't you just validate against something like /\A[\w+\-.]+#(berkeley|uw)\.edu\z/i and be done with it? If you really need to later determine which it is, make a method that just checks the back part, or returns the match, or whatever...
First I think your regex should be changed from [\w+\-.] to [\w+\-\.]
The validation could be
validates :email, format: { with: "\A#{berkely_regex}|#{uw_regex}\z/i" }
but you'll need to remove the flags ( \A, \z, /i ) from the vartiables

How to validate price in input?

I have an input (it's text input) where users can set up the price.
The problem is, that users can sometimes set up the price like this:
9
9.99
9,99
$9.99
What's the best way to validate this input? I am running the app on Heroku (= PostgreSQL database), the data type column is decimal.
Rails 4 complains about using $ and ^, so use:
validates :price, :presence => true,
:format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }
Just trying to save people time ;-)
Try something like below. It matches all you examples.
validates :price, :presence => true,
:format => { :with => /^(\$)?(\d+)(\.|,)?\d{0,2}?$/ }

Ruby ActiveRecord: validate format of an integer field

I'm trying to validate the format of a field in an ActiveRecord. I want this field to either be empty, or contain a sequence of digits only (it is containing an optional port number for a database connection). I'm currently trying this:
validates_format_of :port, with: /\A[0-9]*\Z/, message: 'Only numbers allowed'
but without luck. I've found that adding a required number by using for example {1, 6} sort of works, but makes the field mandatory.
Any advice?
Many thanks in advance,
Joseph.
If you're looking to validate so that only numbers are allowed, then you should be able to use this:
validates :port, :numericality => {:only_integer => true}
You may want to try to validate the numericality of the field, like so:
validates_numericality_of :port, :only_integer => true
:only_integer will ensure that the value entered for :port is an integer.
You can also just add allow_blank: true
You can use this syntax as well
validates numericality: :only_integer

How to add a User model validation to block certain email domains

I would like to have a list of email domains that are validated against to prevent from registering on my app.
10minutemail.com, yopmail.com, mail.com, mail.ru etc...
I have a list of domains in my user model like so:
BAD_DOMAINS = [/10minutemail.com/, /yopmail.com/, /mail/
I would like to add a User validates on the email field to add an error if the user is registering with one of these domains.
BAD_DOMAINS.each { |rule| return true if !domain.match(rule).nil? }
I have that regex working, but how do I add that as a validates? I tried this:
validates :email, :format => { : exclusion => BAD_DOMAINS,
:message => "%{value} no good." }
Thanks
You need to combine all of your separate regular expressions into a singular one, but you might find it's easier to do that if you have a list of strings instead of a list of regular expressions:
EXCLUSION_DOMAINS = %w[
example.com
test.com
asdf.com
]
EXCLUSION_REGEXP = Regexp.new('(?:' + EXCLUSION_DOMAINS.collect { |d| Regexp.escape(d) }.join('|') + ')$')
You'll want to ensure that things don't match this, so it's a little different to use:
validates :email,
:format => {
:with => VALID_EMAIL_REGEXP,
:without => EXCLUSION_REGEXP,
:message => "%{value} no good."
}
You should use some kind of valid email tester as well to be sure the address is plausible. It's expressed here as VALID_EMAIL_REGEXP which is some kind of email validator regular expression. Try and use an RFC compliant one if you do that.

Resources