Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Rails URL Validation (See related posts)

No regexes, allows URLs with ports or IPs. Inspiration from here

  validates_each :href, :on => :create do |record, attr, value|
    begin
      uri = URI.parse(value)
      if uri.class != URI::HTTP
        record.errors.add(attr, 'Only HTTP protocol addresses can be used')
      end
    rescue URI::InvalidURIError
      record.errors.add(attr, 'The format of the url is not valid.')
    end
  end

You need to create an account or log in to post comments to this site.


Click here to browse all 4860 code snippets

Related Posts