4

I have Url model have url column and I want to validate that column to be a valid url, I have try with this:

class User < ActiveRecord::Base
    validates_format_of :url, :with => URI::regexp(%w(http https))
end

But when I enter this url: http://ruby3arabi it's accept it, any ideas?

2

3 Answers 3

14

I tested and found that URI::regexp(%w(http https)) or URI::regexp are not good enough.

The troubleshooting is using this regular expression

/\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\z/ix

Option:

  • i - case insensitive
  • x - ignore whitespace in regex
  • \A - start of regex (safely uses \A for Rails compares to ^ in common case)
  • \z - end of regex (safely uses \z for Rails compares to $ in common case)

So if you want to validate in model, you should use this instead:

class User < ApplicationRecord
  URL_REGEXP = /\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?\z/ix
  validates :url, format: { with: URL_REGEXP, message: 'You provided invalid URL' }
end

Test:

  • [1] URI::regexp(%w(http https))

    Test with wrong urls:

    • http://ruby3arabi - result is invalid
    • http://http://ruby3arabi.com - result is invalid
    • http:// - result is invalid

Test with correct urls:

Test with correct urls:

Test with correct urls:

Credit: Thanks noman tayyab, ref:Active Record Validations for update in case \A and \z

Sign up to request clarification or add additional context in comments.

2 Comments

I would say this is the perfect regex I've been looking for.
Above Regex throws an argument error (a security concern of multiline expressions) in rails 4. The alternate is to use \A for start of string and \z for end.
4

I solved this problem with this gem https://github.com/ralovets/valid_url

1 Comment

This gem is widely out of date in 2020, it will fail with several valid TLDs
2

You should consider using URI.parse: http://ruby-doc.org/stdlib-2.1.1/libdoc/uri/rdoc/URI.html#method-c-parse

2 Comments

Can you explain how to use this with Rails? thank you
There is very good explanation stackoverflow.com/questions/7167895/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.