Rails图像URL验证 [英] Rails Image URL Validation
本文介绍了Rails图像URL验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我在一个表中有记录,每个记录都有一个icon属性,该属性采用以下形式的url:
Let's say I have records in a table, and each has an icon attribute that takes a url of the form:
- balls/x.png
- balls/y.png
- balls/z.png
- …
如何编写验证,以确保网址以"balls/"开头,并以.png,.gif结尾.还是.jpg?
How do I write a validation that makes sure the url starts with "balls/" and ends with either .png, .gif. or .jpg?
我当前的验证只是检查文件扩展名:
My current validation just checks for the file extension:
validates_format_of :icon, :with => %r{\.(gif|jpg|png)$}i, :message => 'must be a URL for GIF, JPG ' + 'or PNG image.'
推荐答案
如何编写验证,以确保网址以"balls/"开头,并以.png,.gif结尾.还是.jpg?
How do I write a validation that makes sure the url starts with "balls/" and ends with either .png, .gif. or .jpg?
这将起作用:
validates_format_of :icon,
:with => %r{^balls/.+\.(gif|jpe?g|png)$}i,
:message => "must start with 'balls/' and have an image extension"
但是您可以在同一字段上进行多个验证.因此,这也将起作用,并且更具可读性:
But you can have multiple validations on the same field. So, this will work too, and is more readable:
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"
这篇关于Rails图像URL验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文