Use error_tag without the span or with a different class

Viewed 959

I use Tailwind CSS 2.0 in a Phoenix application. The error_tag in a form gives me a headache:

<div>
  <label for="password" class="block text-sm font-medium text-gray-700">
    Passwort
  </label>
  <div class="mt-1">
    <%= password_input f, :password, required: true, id: "password", type: "password", 
        autocomplete: "new-password", 
        class: "appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md 
                shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 
                focus:border-indigo-500 sm:text-sm" 
    %>
    <p class="mt-2 text-sm text-gray-500"><%= error_tag f, :password %></p>
  </div>
</div>

Which results in this HTML:

<p class="mt-2 text-sm text-gray-500">
<span class="invalid-feedback" phx-feedback-for="user_password">
  should be at least 8 character(s)
</span>
</p>

and this rendering:

enter image description here

Question: Can I force error_tag not to render the <span>, use a different class or can I access the error message without the error_tag?

I tried to solve this by googling error_tag and class but that didn't result into any helpful article.

3 Answers

This is the implementation of error_tag/2

def error_tag(form, field) do
  Enum.map(Keyword.get_values(form.errors, field), fn error ->
    content_tag(:span, translate_error(error),
      class: "invalid-feedback",
      phx_feedback_for: input_name(form, field)
    )
  end)
end

That said, I see many different approaches to handle the issue:

I would go with raw content_tag/2.

Can you try to change to a different class like this?

<%= error_tag f, class: "New class", :password %>

Update the default error_helpers.ex file in your views directory to 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

Fixed it for me and my error messages are displaying properly

Related