1

I want to limit user to select up to 2 files (in the input tag ?).

 <%= f.file_field :images, multiple: true %>

I would like to limit user to select up to 2 files (front and backoffice).

Is there a way (preferable a hard coded option) to limit the number of files that user can select?

Ben
  • 660
  • 5
  • 25
  • This is really not a Rails issue if you're thinking about limiting it in the UI, all the `file_field` does is just spit out some `input type='file'` html tag https://stackoverflow.com/questions/10105411/how-to-limit-the-maximum-files-chosen-when-using-multiple-file-input – Eyeslandic May 02 '19 at 18:44
  • Possible duplicate of [Count and limit the number of files uploaded (HTML file input)](https://stackoverflow.com/questions/9813556/count-and-limit-the-number-of-files-uploaded-html-file-input) – Eyeslandic May 02 '19 at 18:45

2 Answers2

0

You cannot specify a limit. Javascript can detect the number of files or your Ruby backend can detect the number of files, but you have to do validation outside the HTML.

If you have a small, hardcoded, number of file fields, you can always create a unique form_field for each and force the user to update each one separately and then submit them in an array to the backend.

Veridian Dynamics
  • 1,405
  • 1
  • 9
  • 19
0

The short answer is no. Behind the scenes Rails is just generating markup. Per the source code at https://github.com/rails/rails/blob/1ce5153a099e82f761315154dfe5e01253dafd81/actionview/lib/action_view/helpers/form_helper.rb#L1202

#   file_field(:post, :image, multiple: true)
#   # => <input type="file" id="post_image" name="post[image][]" multiple="multiple" />

Rails is just setting the multiple attribute to "multiple". You might be able to achieve what you're after with JavaScript. You could also just output two file upload inputs without the multiple attribute...

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38