endymion

endymion

Cleanly add custom errors for Ecto.Changeset.cast/4

Found a clean solution for adding custom error messages when using Ecto.Changeset.cast/4.

The issue presented is cast/4 does not allow :message for an opts unlike other changeset functions like validate_format/4 and other custom validator functions.

This presented a problem for us as we have a number of custom types and messages that we use to validate our inputs. This works fine when validating things like a phone number because we can simply pass our custom error message directly to validate_format/4, but for our :integer and :float values we simply rely on the base cast/4 for those types without the need for more validation. When given "foo" to input type :float the changeset error message returns "is invalid". Using Gettext and traverse_errors/2 we can fix this error message on the UI, but that ends up in needing to have branching error message logic and makes it more difficult with a dozen types to clearly see where the error message definitions exist.

Instead we have a function custom_cast_error_message(changeset, field, message) that replaces the given field error only for cast/4 validations to be our custom message

  @doc """
  Overwrites the error message for `Ecto.Changeset.cast/4` from `"is invalid"` to the
  custom supplied error message.
  """
  def custom_cast_error_message(changeset, field, message) do
    errors = Enum.map(changeset.errors, fn {error_field, {_msg, opts}} = error ->
      if field == error_field && opts[:validation] == :cast do
        {field, {message, opts}}
      else
        error
      end
    end)

    %{changeset | errors: errors}
  end

A sample usage of this looks like

message = "This is our custom error message for cast/4"

Ecto.Changeset.cast(answer, params, [:value])
|> Aw.Changeset.custom_cast_error_message(:value, message)

Posting this because I saw numerous posts about this same issues and didn’t love the solutions found.

Most Liked

cjbottaro

cjbottaro

My initial thought was to do this in translate_errors using the error metadata, but I like this better since it keeps the error messages all in one place and not spread out… :+1:

LostKobrakai

LostKobrakai

defmodule PhoneNumberType do
  use Ecto.Type

  def type, do: :string

  def cast(value) do
    case Ecto.Type.cast(:string, value) do
      {:ok, value} -> {:ok, value}
      :error -> {:error, "Our custom phone number error message here"}
    end
  end

  def dump(value), do: Ecto.Type.dump(:string, value)
  
  def load(value), do: Ecto.Type.load(:string, value)
end

defmodule UnionStruct.PhoneNumber do
  use Ecto.Schema

  embedded_schema do
    field :other_data, :any
    field :value, PhoneNumberType
  end

  def changeset(changeset, params, opts) do
    Ecto.Changeset.cast(changeset, params, [:value], opts)
    |> validate_phone_number(:value)
  end
end

You can wrap generic types like this to get more specific types. If you have many similar ones you can even abstract this using Ecto.ParameterizedType.

Last Post!

LostKobrakai

LostKobrakai

defmodule CustomString do
  use Ecto.ParameterizedType

  def init(opts) do
    %{error: opts[:validation_message]}
  end

  def type(_), do: :string

  def cast(value, params) do
    case Ecto.Type.cast(:string, value) do
      {:ok, value} -> {:ok, value}
      :error -> {:error, params.error}
    end
  end

  def dump(value, _, _), do: Ecto.Type.dump(:string, value)
  def load(value, _, _), do: Ecto.Type.load(:string, value)
end

defmodule UnionStruct.PhoneNumber do
  use Ecto.Schema

  embedded_schema do
    field :value, CustomString, validation_message: "abc"
  end

  def changeset(changeset, params, opts) do
    Ecto.Changeset.cast(changeset, params, [:value], opts)
    |> validate_phone_number(:value)
  end
end

Where Next?

Popular in Discussions Top

PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31695 143
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
joeerl
I’m playing with Elixir - It’s fun. I think @rvirding does give Elixir courses these days. Re: files and database - when I given Erlang ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
Fl4m3Ph03n1x
Background A few days ago I was listening to The future of Elixir from Elixir Talks, with Dave Thomas (@pragdave ) and Brian Mitchell. I...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54006 488
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement