如果 URL 不存在,则将 http(s) 添加到 URL? [英] Add http(s) to URL if it's not there?
本文介绍了如果 URL 不存在,则将 http(s) 添加到 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的模型中使用这个正则表达式来验证用户提交的 URL.我不想强迫用户输入 http 部分,但如果它不存在,我想自己添加它.
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 not there.
validates :url, :format => { :with => /^((http|https):\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(\/.)?$/ix, :message => " is not valid" }
知道我怎么做吗?我对验证和正则表达式的经验很少..
Any idea how I could do that? I have very little experience with validation and regex..
推荐答案
如果它不存在,请使用 before 过滤器添加它:
Use a before filter to add it if it is not there:
before_validation :smart_add_url_protocol
protected
def smart_add_url_protocol
unless url[/\Ahttp:\/\//] || url[/\Ahttps:\/\//]
self.url = "http://#{url}"
end
end
留下你的验证,这样如果他们打错了他们可以纠正协议.
Leave the validation you have in, that way if they make a typo they can correct the protocol.
这篇关于如果 URL 不存在,则将 http(s) 添加到 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文