Simple Phoenix LIveView App: New & Form Validations

Last time we set up some PubSub helpers in Accounts.ex, migrated the users index page to LiveView

In this episode, we'll start converting the new users page and form into live views. In the process, we'll get to see LiveView and Phoenix form validations in action.

Restricting errors to specific fields (covered later in this series)

In order for LiveView to be able to association Ecto validation errors with specific form fields, the forms need to have a specific phx_error_for data attribute. You can add this to your forms by changing your &error_tag/2 function.

Inside error_helpers.ex Change:

  def error_tag(form, field) do, field), fn error ->
      content_tag(:span, translate_error(error), class: "help-block")

to this:

  def error_tag(form, field) do
    |> Keyword.get_values(field)
    |> error ->
      content_tag(:span, translate_error(error),
        class: "help-block",
        data: [phx_error_for: input_id(form, field)]
Back to index

No Comments