endymion
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.
Trending in Discussions
Other Trending Topics
Latest Phoenix Threads
Chat & Discussions>Discussions
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex











First 6 of 6 Posts
cjbottaro
My initial thought was to do this in
translate_errorsusing the error metadata, but I like this better since it keeps the error messages all in one place and not spread out…LostKobrakai
Ecto types can already return custom error messages. For cast customizing the error doesn‘t really make sense as you‘d never really use it for individual fields.
endymion
That doesn’t work in our case. We have a union type that contains multiple
embeds_onewhich delegates the specific validation logic for each type.For the fields like
[:url, :phone_number, :ssn]those are all:stringEcto types. Hence why we can not have a single custom error message for:stringwhen casting a value to:url, as the message we want to present with the input:urlor:phone_numberis different.LostKobrakai
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.endymion
This was my first thought at addressing this issue, we have several custom Ecto types that such as our own date format that we can do this for. But our total number of types we would need to do this for is around 12. Maintaining those custom 12 types just to set a cast message didn’t feel like a good trade off for the long run.
LostKobrakai