Reputation: 14736
I'm searching for a way to validate a field for correct URL or IP address in a rails model. I've played a little bit with validates :url, :format => URI::regexp(%w(http https))
, and other URL validations. But how do I get the field validated with either an URL or an IP address? Maybe there is a gem for that.
thx!
Upvotes: 1
Views: 830
Reputation: 12818
Not sure if there are such gems, but custom validations can be implemented relatively simple (with ipaddress
gem in the Gemfile). Try something like
require 'uri'
validate :valid_url_or_ip
...
private
def valid_url_or_ip
unless valid_url?(url) || IPAddress.valid?(url)
errors.add(:url, "Not an URL or IP address")
end
end
def valid_url?
uri = URI.parse(url)
uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
rescue URI::InvalidURIError
false
end
Upvotes: 2