Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation for file size in rails before being uploaded

in my form i have

<%= label_tag("file", "Attachment:") %><%= file_field_tag "uploadfile" %>

In my model i would like to write this

validate :validates_uploadfile

def validates_uploadfile(file)
    max_size = 2048
    errors.add(:uploadfile, "File size exceeds limitation") if file.size > max_size
end

In my controller can i call something like this

validates_upload_file(params[:uploadfile])

Is there a way to validate a file upload before being uploaded(not by using javascript or by looking at the file extension)
Thanks for the help

UPD

validate :uploadfile_validation, :if => "uploadfile?"

def uploadfile_validation
    errors[:uploadfile] << "should be less than 1MB" if uploadfile.size > 1.megabytes
end
like image 845
Hishalv Avatar asked Jun 22 '11 13:06

Hishalv


Video Answer


1 Answers

Here's my code for size validations (I use CarrierWave for uploads).

  validate :picture_size_validation, :if => "picture?"  

  def picture_size_validation
    errors[:picture] << "should be less than 1MB" if picture.size > 1.megabytes
  end

Cheers.

like image 98
Lucas Avatar answered Oct 18 '22 21:10

Lucas