When using Ecto.Changeset.validate_length/3, the error message when the string is less than the minimum characters is “should be at least %{count} character(s)”
.
What is the simplest way to replace %{count}
with the actual minimum number of characters when the message is passed back as an error?
Also, just curious, is there a reason the function doesn’t insert the count for you?
Thanks!
Axel
2 Likes
I just found Ecto.Changeset.traverse_errors/2 uses this exact situation as the example.
error message:
{"should be at least %{count} characters", [count: 3, validation: :length, min: 3]}
function:
traverse_errors(changeset, fn {msg, opts} ->
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
%{title: ["should be at least 3 characters"]}
4 Likes