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
- …
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.'
How do I write a validation that makes sure the url starts with "balls/" and ends with either .png, .gif. or .jpg?
This will work:
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"
How about a straight regex like:
validates_format_of :icon, :with => %r{^(balls\/)[A-Za-z]+\.(gif|jpg|png)$}i, :message => 'icon must start with balls'