Make user-inputted url into external link in rails

前端 未结 2 1722
忘掉有多难
忘掉有多难 2021-01-14 10:10

I want users to be able to enter a url and then put a link to that url in my view.

Valid inputs could be e.x. https://www.google.com/path, http:/

相关标签:
2条回答
  • 2021-01-14 10:41

    The Domainatrix gem comes highly recommended for validating URLs:

    https://github.com/pauldix/domainatrix

    0 讨论(0)
  • 2021-01-14 10:56

    Check this out:

    validates_format_of :website, :with => URI::regexp(%w(http https))  
    

    Source: http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company

    To format a URL that is missing the protocol (http or https), I would do a before_save hook that prepends it if it's missing:

    before_save :format_url
    
    ...
    
    def format_url
      self.website = "http://#{self.website}" unless self.website[/^https?/]    
    end
    
    0 讨论(0)
提交回复
热议问题