Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate url in rails model?

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?

like image 801
AliOsm Avatar asked Dec 01 '22 13:12

AliOsm


1 Answers

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:

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

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

  • https://www.ruby3arabi.com - result is invalid

  • https://www.ruby3arabi.com/article/1 - result is invalid

  • https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - result is invalid

  • [2] URI::regexp

    Test with wrong urls:

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

Test with correct urls:

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

  • http://www.ruby3arabi.com - result is valid

  • https://www.ruby3arabi.com - result is valid

  • https://www.ruby3arabi.com/article/1 - result is valid

  • https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - result is valid

  • [3] /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(/.)?$/ix

    Test with wrong urls:

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

Test with correct urls:

  • http://ruby3arabi.com - result is valid
  • http://www.ruby3arabi.com - result is valid
  • https://www.ruby3arabi.com - result is valid
  • https://www.ruby3arabi.com/article/1 - result is valid
  • https://www.ruby3arabi.com/websites/58e212ff6d275e4bf9000000?locale=en - result is valid

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

like image 99
Komsun K. Avatar answered Dec 04 '22 03:12

Komsun K.