Quick Tip: URL Validation in Rails

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!