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

mbenatti
Following https://github.com/tbrand/which_is_the_fastest |> https://raw.githubusercontent.com/tbrand/which_is_the_fastest/master/imgs...
New
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
und0ck3d
Hello everyone! A few days ago I’ve created a topic here about how people were creating CMSs with Elixir and Phoenix. I’ve been studying...
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
eteeselink
Hi all, In the last days, two things happened: A blog post titled “They might never tell you it’s broken” made the rounds. It’s about ...
New
thojanssens1
It would be nice to be able to define a redirect from one route to another from the router.ex file. E.g.: redirect "/", UserController, ...
New
Rustixir
Hi everyone, im working on find best language/framework/system for high concurrency, high performance and stable performance after wor...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130286 1222
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New

We're in Beta

About us Mission Statement