Ruby on rails 友好的表单验证(Rails)
我检查了之前提出的问题,这些问题对我的案例有帮助,但不是一个完整的解决方案 本质上,我需要验证用户从表单提交的URL。我首先验证它是否以http://、https://、或ftp://开头:Ruby on rails 友好的表单验证(Rails),ruby-on-rails,ruby,forms,validation,Ruby On Rails,Ruby,Forms,Validation,我检查了之前提出的问题,这些问题对我的案例有帮助,但不是一个完整的解决方案 本质上,我需要验证用户从表单提交的URL。我首先验证它是否以http://、https://、或ftp://开头: class Link < ActiveRecord::Base validates_format_of [:link1, :link2, :link3, :link4, :link5], :with => /^(http|https|ftp):\/\/.*/ end cl
class Link < ActiveRecord::Base
validates_format_of [:link1, :link2, :link3,
:link4, :link5], :with => /^(http|https|ftp):\/\/.*/
end
class链接/^(http | https | ftp):\/\/*/
结束
这对它所做的工作非常有效,但我需要进一步执行以下两个步骤:
我很难确定如何使这项工作干净高效。仅供参考,您不必向
传递数组来验证的格式。Ruby将自动生成数组(Rails解析*args
的输出)
所以,对于你的问题,我会选择这样的方式:
class Link < ActiveRecord::Base
validate :proper_link_format
private
def proper_link_format
[:link1, :link2, :link3, :link4, :link5].each do |attribute|
case self[attribute]
when nil, "", /^(http|https|ftp):\/\//
# Allow nil/blank. If it starts with http/https/ftp, pass it through also.
break
else
# Append http
self[attribute] = "http://#{self[attribute]}"
end
end
end
end
class链接
仅供参考,您不必向传递数组来验证的格式。Ruby将自动生成数组(Rails解析*args
的输出)
所以,对于你的问题,我会选择这样的方式:
class Link < ActiveRecord::Base
validate :proper_link_format
private
def proper_link_format
[:link1, :link2, :link3, :link4, :link5].each do |attribute|
case self[attribute]
when nil, "", /^(http|https|ftp):\/\//
# Allow nil/blank. If it starts with http/https/ftp, pass it through also.
break
else
# Append http
self[attribute] = "http://#{self[attribute]}"
end
end
end
end
class链接
为了补充上述内容,我使用Ruby URI模块解析URL的有效性
它工作得非常好,它帮助我避免正则表达式。我使用Ruby URI模块解析URL的有效性
它工作得非常好,帮助我避免正则表达式