DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails URL Validation

09.12.2007
| 8367 views |
  • submit to reddit
        No regexes, allows URLs with ports or IPs. Inspiration from <a href="http://actsasblog.wordpress.com/2006/10/16/url-validation-in-rubyrails/">here</a>

  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