Tutorial
Quicktip: Customize look of form validation in Phoenix
This post was updated 01 May - 2020
formsphoenix
When submitting a form in a Phoenix and get validation errors, you are displayed with a little validation error text. However, you probably want to customize how that error message is displayed. For example, what I don't like is that it just say
"`can't be blank`"
And also, the class that is attached is not compatible with Tailwind or Bootstrap. So, for my use case I want it to have both the field name attached and some Tailwind classes.
To accomplish that, you can do that in the file: `lib/tutorial_web/views/error_helpers.ex`
So, out of the box, the code looks something like this:
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error), class: "help-block")
end)
end
And change it to something like this:
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
field = field |> Atom.to_string() |> String.capitalize()
content_tag(:span, "#{field} #{translate_error(error)}", class: "block mt-1 text-sm text-red-700")
end)
end
### END RESULT
