How add error to @uploads for live_file_input?

I have a form that uses liveview file upload. I would like to check that the user has selected the file and if not, display an error.

In the heex file I use .live_file_input and then display the error in the style:

<%= for err <- upload_errors(@uploads.input_file) do %>
   <p class="alert alert-danger"><%= error_to_string(err) %></p>
<% end %>

Is there any way to add a custom error to @uploads? Alternatively, how to show the error if the user has not selected the file?

Thanks

I solved it by adding a custom variable @custom_error and checking if a file is selected during the save event.

In ex:

if Enum.empty?(uploaded_files) do
      socket = assign(socket, :custom_errors, ["File must be selected!"])
      {:noreply, socket}
    else
      ...

In Heex:

<%= if @custom_errors != [] do %>
  <.error :for={msg <- @custom_errors}><%= msg %></.error>
<% end %>
1 Like