【问题标题】:Rails Image URL ValidationRails 图像 URL 验证
【发布时间】:2011-07-11 03:51:18
【问题描述】:

假设我在一个表中有记录,每个记录都有一个图标属性,该属性采用表单的 url:

  • balls/x.png
  • balls/y.png
  • balls/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.'

【问题讨论】:

    标签: ruby-on-rails image validation url


    【解决方案1】:

    如何编写验证以确保 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"
    

    【讨论】:

      【解决方案2】:

      直接的正则表达式怎么样:

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

      【讨论】:

        猜你喜欢
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 2011-04-24
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多