Add http(s) to URL if it's not there?

前端 未结 7 1952
抹茶落季
抹茶落季 2020-12-08 19:27

I\'m using this regex in my model to validate an URL submitted by the user. I don\'t want to force the user to type the http part, but would like to add it myself if it\'s n

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 19:41

    The accepted answer is quite okay. But if the field (url) is optional, it may raise an error such as undefined method + for nil class. The following should resolve that:

    def smart_add_url_protocol
      if self.url && !url_protocol_present?
        self.url = "http://#{self.url}"
      end
    end
    
    def url_protocol_present?
      self.url[/\Ahttp:\/\//] || self.url[/\Ahttps:\/\//]
    end
    

提交回复
热议问题