Make user-inputted url into external link in rails

☆樱花仙子☆ 提交于 2020-01-29 17:54:29

问题


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://www.google.com, www.google.com

Is there are standard rails way to 1) validate that input is a valid url format and 2) convert that third format to http://www.google.com in my views so the external link works?

I don't want to re-invent the wheel if I can avoid it.


回答1:


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



回答2:


The Domainatrix gem comes highly recommended for validating URLs:

https://github.com/pauldix/domainatrix



来源:https://stackoverflow.com/questions/8155551/make-user-inputted-url-into-external-link-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!