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:
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