Validate an file input in Pheonix Live View

Hi all,

I am rendering a form related to this schema in a live view:

defmodule Storybook.Examples.Schemas.Person do
  use Ecto.Schema
  import Ecto.Changeset

  embedded_schema do
    field(:avatar, :string)

  def changeset(user, attrs \\ %{}) do
    user |> cast(attrs, [:avatar]) |> validate_required([:avatar])

The avatar field should be the path of an uploaded file.

In the template of the live view I binded the phx-change and phx-submit events like it’s explained here: Uploads — Phoenix LiveView v0.18.18

What I am not getting is how to validated the fact that the :avatar field is required.
In the phx-change callback I don’t get it in the params.

I hope I’ve been clear enough about my goal, otherwise I can paste some more code.

Thank you

Hi @elnovice,

You will need to rename the file and add the filename to your parameters that you send to the changeset.

It is explained in this article: How to Do Live Uploads in Phoenix LiveView | AppSignal Blog - around “Consume Uploaded Entries”. The relevant code from the article is:

  def handle_event("save", product_params, socket) do
    file_path =
      consume_uploaded_entry(socket, :image, fn %{path: path}, _entry ->
        dest = Path.join("priv/static/uploads", Path.basename(path))
        File.cp!(path, dest)
        Routes.static_path(socket, "/uploads/#{Path.basename(dest)}")
    # This is where the form parameters have the filename added
    # save_product will go and do the changeset and Repo saving bits
    product = save_product(Map.put(product_params, :image_upload, file_path)
      |> push_redirect(to: Routes.product_show_path(socket, :show, product))}
1 Like

Very useful article, thank you.