romenigld

romenigld

Hello Guys,
I was doing the course of the PraProg Phoenix LiveView Pro and I was trying to do a validation for the upload files.
For example If I try to put just the name of the desks and not put any file for upload, I would like to show the validation for upload a file.

I tried to add a validate_required for the photo_urls on the changeset:

 defmodule LiveViewStudio.Desks.Desk do
  use Ecto.Schema
  import Ecto.Changeset

  schema "desks" do
    field :name, :string
    field :photo_urls, {:array, :string}, default: []

    timestamps()
  end

  @doc false
  def changeset(desk, attrs) do
    desk
    |> cast(attrs, [:name, :photo_urls])
    |> validate_required([:name, :photo_urls])
  end
end

But if I put just the name for the desks, the photo_urls are not validated.
as you can see the log:

[debug] QUERY OK db=2.1ms queue=1.3ms idle=1529.6ms
INSERT INTO "desks" ("name","photo_urls","inserted_at","updated_at") VALUES ($1,$2,$3,$4) RETURNING "id" ["Testing", [], ~N[2021-04-19 17:20:41], ~N[2021-04-19 17:20:41]]

But on the application this values are not showed. It shows only the those which have photo_urls.
But If I try to list all Desks, like:
iex> Desks.list_desks()
The empty photo_urls are recorded:

  %LiveViewStudio.Desks.Desk{
    __meta__: #Ecto.Schema.Metadata<:loaded, "desks">,
    id: 17,
    inserted_at: ~N[2021-04-16 21:11:22],
    name: "Testing",
    photo_urls: [],
    updated_at: ~N[2021-04-16 21:11:22]
  },

How can I validate an empty array of strings for the :photo_urls?

Showing Posts 1 to 10

cenotaph

cenotaph

I didn’t get your goal, are you after validating photo_urls are empty?

I was reading into the Ecto.Changeset.validate_required, I don’t think it works on lists but single value fields instead.

romenigld

romenigld OP

What I want is to validate the array of string which in this case is the :photo_urls.

cenotaph

cenotaph

In that case you would have to define your own validation in your schema. Keep in mind you would be only validating the string url for those files at that point, not the files themselves.

You can iterate over the urls and use validate_format maybe if you are expecting a certain file path or minimum number of urls.

romenigld

romenigld OP

sorry but on Docs I don’t see any validate_pattern?

cenotaph

cenotaph

my apologies, different language mix up there! I have corrected my post

romenigld

romenigld OP

don’t worry. I will see.
Thank you for reply @cenotaph !

f0rest8

f0rest8

I know, in general, the PragProg course doesn’t cast the :photo_urls because you build them explicitly during the live upload process.

I’m guessing you want to add extra info for the person’s experience using the upload, in which case you could try some type of logic in your template like:

<%= if @uploads.desk.entries == [] do %>
  # render your error
  # disable the upload button, etc.
<% end %>

Something like that may be what you’re after? And you can adjust your conditional accordingly.

romenigld

romenigld OP

Yes I know in the course it doesn’t cast the :photo_urls.
But I was testing to put just the :name and no files for uploads.
And then I notice it was saving on the database, but they don’t are showing.
So I was trying to do a validate in the schema.
For now your help make more sense.
But it would be nice to do this on the schema.
I will review some books, I think I saw something which is possible creating a custom validation.
I just don’t know how to do it now.
thank you for reply @f0rest8!

romenigld

romenigld OP

I was thinking to try a custom validation(something like this):

  @doc false
  def changeset(desk, attrs) do
    desk
    |> cast(attrs, [:name, :photo_urls])
    |> validate_required([:name])
    |> validate_empty_photo_urls(:photo_urls)
  end

  def validate_empty_photo_urls(changeset, field)  do
    validate_change(changeset, field, fn _field, value ->
      cond do
        is_nil(value) -> "must insert a photo!"
      end
    end)
  end

But not work’s!
Can anyone help me with this custom validation?

sfusato

sfusato

It invokes the validator function to perform the validation only if a change for the given field exists and the change value is not nil. The function must return a list of errors (with an empty list meaning no errors).

  • when the value is nil, the validator function won’t even be called; I believe you defined :photo_urls as an array of strings with the default value being empty list;
  • you must return a list of errors, [photo_urls: "must insert a photo!"], in the error case
  • [] in the no error case

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews