Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active February 23, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujanfernaud/fa76c3ab88d0e6eb08a0ec5c045ec5d1 to your computer and use it in GitHub Desktop.
Save lujanfernaud/fa76c3ab88d0e6eb08a0ec5c045ec5d1 to your computer and use it in GitHub Desktop.
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