Validation for URL/Domain using Regex? (Rails)

Stumbled on this:

validates_format_of :domain_name, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix

FYI: Rubular is a fantastic resource for testing your Ruby regular expressions


@Tate's answer is good for a full URL, but if you want to validate a domain column, you don't want to allow the extra URL bits his regex allows (e.g. you definitely don't want to allow a URL with a path to a file).

So I removed the protocol, port, file path, and query string parts of the regex, resulting in this:

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$


Check out the same test cases for both versions.

  • Original (allows domains or full URLs): http://rubular.com/r/qGInC06jcz
  • Modified (allows only domains): http://rubular.com/r/yP6dHFEhrl