Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby: Validate URL

Ruby: Validate URL

We can match against %r{^(http|https)://[a-z0-9]+([\-.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$}ix.

Non Rails version:

  VALID_URL_REGEXP = %r{^(http|https)://[a-z0-9]+([\-.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$}ix.freeze

  def valid_url?(url)
    !url.empty? && url.match?(VALID_URL_REGEXP)
  end

Rails version:

  VALID_URL_REGEXP = %r{^(http|https)://[a-z0-9]+([\-.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$}ix.freeze

  def valid_url?(url)
    url.present? && url.match?(VALID_URL_REGEXP)
  end

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment