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

Phoenix Boilerplate

Generate a Phoenix Boilerplate and save hours on your next project.

Try now

SAAS Starter Kit

Get started and save time and resources by using the SAAS Starter Kit built with Phoenix and LiveView.

Learn More

Related Tutorials

Published 14 Feb - 2020

Improving LiveView UX with Phoenix Channels - Tagging part 3

channelsformsliveviewphoenixtagging

In the previous tutorial I set up the tagging interface. It had however a small issue. If I added a tag, it didnt really refocus on the input so I n..

Published 13 Feb - 2020

Tagging interface with Phoenix LiveView and Tailwind - Tagging part 2

formsliveviewphoenixtaggingtailwindtypeahead

In the previous tutorial, I set up the the backend for being able to add tags to products. I have also written a tutorial about adding a LiveView an..