Rails图像URL验证

时间:2011-07-11 03:51:18

标签: ruby-on-rails image validation url

假设我在表格中有记录,每个记录都有一个图标属性,其中包含以下形式的网址:

  • 球/ x.png
  • 球/ y.png
  • 球/ z.png
  • ...

如何编写验证,确保url以“balls /”开头,以.png,.gif结尾。还是.jpg?

我当前的验证只检查文件扩展名:

validates_format_of :icon, :with => %r{\.(gif|jpg|png)$}i, :message => 'must be a URL for GIF, JPG ' + 'or PNG image.'

2 个答案:

答案 0 :(得分:6)

  

如何编写验证,确保url以“balls /”开头,以.png,.gif结尾。还是.jpg?

这将有效:

validates_format_of :icon,
  :with    => %r{^balls/.+\.(gif|jpe?g|png)$}i,
  :message => "must start with 'balls/' and have an image extension"

但是您可以在同一个字段上进行多次验证。所以,这也会起作用,而且更具可读性:

validates_format_of :icon,
  :with    => %r{^balls/.+}i,
  :message => "must start with 'balls/' and have a filename"

validates_format_of :icon,
  :with    => %r{\.(gif|jpe?g|png)$}i,
  :message => "must have an image extension"

答案 1 :(得分:0)

直接正则表达怎么样:

validates_format_of :icon, :with =>  %r{^(balls\/)[A-Za-z]+\.(gif|jpg|png)$}i, :message => 'icon must start with balls'