0

How can I validate that the structure of a url is correct ?, the urls may or may not contain http or https.

For example:

  • www.google.com - is valid
  • https://www.google.com - is valid
  • www.google,com - is invalid
  • www.google - is invalid

I try the code of this question:

Validation for URL/Domain using Regex? (Rails)

validates :url_soporte, :url_privacidad, :web_site, :format => {
      :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix,
      :message => 'You provided invalid URL'
  }, :allow_blank => true

I get this error:

The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?

and URI.regexp does not work for me

How can i fix this?

1 Answers1

0

Why complicate things with a regex?

You could have a custom validator that just created a URI resource and confirmed that it has a host?

def validate_url(url)
  uri = URI.parse(url)

  # raise errors if uri.host is nil
end

This way you can leave the uri package to worry about whether you have a valid domain in your URL, rather than trying to replicate the regex yourself.

Jon
  • 10,678
  • 2
  • 36
  • 48