Rails beginner
Rails beginner

Reputation: 14504

Rails how to validate file format?

How do I validate my file fields for the correct format?

I want the image field to validate that it is a .png, .jpg, .jpeg.

And the flv that it has the ending .flv

And the quicktime that it have the ending .mov

And how do I create error messages to tell that the field is not valid.

My simple_form_for:

<%= f.input :name, :label => 'Navn', :required => true %><br />
<%= f.label :tekst %><br />
<%= f.text_area :text, :label => 'Text', :size => '12x12' %><br />
<%= f.label "Upload billede - kræves" %><br />
<%= f.input :image, :label => '', :required => true %><br />
<%= f.label "Upload flv - kræves" %><br />
<%= f.input :flv, :label => '', :required => true %><br />
<%= f.label "Upload Quicktime - kræves"  %><br />
<%= f.input :quicktime, :label => '', :required => true %><br />
<%= f.button :submit, :value => 'Create movie' %>

Update:

I have figure out how to validate the .mov and .flv fields:

validates_format_of :flv, 
:with => %r{\.flv$}i, :message => "file must be in .flv format"

validates_format_of :mov, 
:with => %r{\.mov$}i, :message => "file must be in .mov format"

I just don´t have found a solution to validate the image.

My controller:

def savenew
    @photographer = Photographer.new(params[:photographer]) 
    @photographer.sort_order = Photographer.count + 1

    if @photographer.save   
      redirect_to :action => 'list', :id => params[:id]
      flash[:notice] = "Movie #{@photographer.name} is created"
    else    
      render 'create', :id => params[:id]             
    end                                 
end         

Upvotes: 3

Views: 15326

Answers (1)

Marten Veldthuis
Marten Veldthuis

Reputation: 1910

If you want to continue as with flv and mov, you could do:

validates_format_of :image, :with => %r{\.(png|jpg|jpeg)$}i, :message => "whatever"

but please be aware that this would only validate that the filename would end in a specific string. These don't validate that the actual file is a real PNG (or whatever format). So someone could still just upload a zipfile with extension ".png".

Upvotes: 12

Related Questions