Back to Blog

Get in Touch

Quick Tip: URL Validation in Rails

By Michael Bleigh February 18, 2009 in rails, validation, quick tip, url

Missing

After doing a quick Google Search I realized that everyone might not know about a great way to do URL validation in Rails. The secret is a little-known method of the URI class, regexp. It lets you generate a regular expression for matching URLs based on an array of accepted protocols. What’s even better, it can be plugged directly into Rails’s validates_format_of. It’s this easy:

class User
  validates_format_of :website, :with => URI::regexp(%w(http https))
end

This will match anything that URI.parse will recognize, meaning that it’s a pretty accurate and powerful URL matcher. URL validation was one of those little annoyances in writing Rails models because it really seemed like there should be an easier way. I found mine, so I thought I’d share it!

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...