Skip to content

Instantly share code, notes, and snippets.

@qcam
Created May 19, 2014 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qcam/45c14301ecefc251e253 to your computer and use it in GitHub Desktop.
Save qcam/45c14301ecefc251e253 to your computer and use it in GitHub Desktop.
Validate URLs in Rails (https://coderwall.com/p/ztig5g)
class UrlValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value)    
  end

  # a URL may be technically well-formed but may 
  # not actually be valid, so this checks for both.
  def url_valid?(url)
    url = URI.parse(url) rescue false
    url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS)
  end 
end

Save it in your app directory so it's autoloaded, eg:

app/validators/url_validator.rb

And use it in your model

class Something < ActiveRecord::Base
    validates :link, url: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment