All posts

Validating a string is a URL in Rails


Tried for a while to find a good example of this in Rails and ultimately came up with the following code:

  validates :url,
    allow_nil: true,
    format: { :with => URI::regexp(%w(https)), :message => "URL must be HTTPS"}

This ActiveRecord validation will use the Kernels URI::regexp to check for a regex match on the URL string for https, if the check fails an error will be returned on the object along with the message provided. If you need to validate for for both http and https you can pass an array to the regex:

URI::regexp(%w([http, https])

Further reading: