dMi*_*Mix 27 regex ruby-on-rails
I am trying to create a validation that checks to make sure a domain/url is valid for example "test.com"
def valid_domain_name?
domain_name = domain.split(".")
name = /(?:[A-Z0-9\-])+/.match(domain_name[0]).nil?
tld = /(?:[A-Z]{2}|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info|me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name[1]).nil?
if name == false or tld == false
errors.add(:domain_name, 'Invalid domain name. Please only use names with letters (A-Z) and numbers (0-9).')
end
end
Run Code Online (Sandbox Code Playgroud)
This is what I have so far but it doesn't work. It lets bad URLs through without failing.
I don't know regex very well.
Tat*_*son 54
偶然发现:
validates_format_of :domain_name, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
Run Code Online (Sandbox Code Playgroud)
仅供参考:Rubular是测试Ruby正则表达式的绝佳资源
Bri*_*Ray 26
@Tate的答案适用于完整的URL,但如果要验证domain列,则不希望允许其正则表达式允许的额外URL位(例如,您绝对不希望允许带有路径的URL文件).
所以我删除了正则表达式的协议,端口,文件路径和查询字符串部分,结果如下:
^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$
查看两个版本的相同测试用例.
jan*_*ane 12
^(http|https):\/\/|[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$/ix
Run Code Online (Sandbox Code Playgroud)
http://rubular.com/r/cdkLxAkTbk
添加了可选的http://或https://
最长的顶级域名.museum,有6个字符......
vit*_*hal 10
在Rails中进行URL验证的另一种方法是
validates :web_address, :format => { :with => URI::regexp(%w(http https)), :message => "Valid URL required"}
Run Code Online (Sandbox Code Playgroud)
require 'uri'
def valid_url?(url)
url.slice(URI::regexp(%w(http https))) == url
end
Run Code Online (Sandbox Code Playgroud)