Feature

Basic LiveView form validation

Preview

Inline form validation basically comes out of the box if you generate a new LiveView app. However, if you want to try it out or add it afterwards, this feature can show you how you can very easily implement it.

lib/phoenix_features_web/live/components/form_validation_simple.ex
defmodule PhoenixFeaturesWeb.Components.FormValidationSimple do
  use PhoenixFeaturesWeb, :live_component

  alias PhoenixFeatures.Products
  alias PhoenixFeatures.Products.Product

  @impl true
  def update(assigns, socket) do
    product = %Product{} # Or get it from assigns or the database

    changeset = Products.change_product(product)

    {:ok,
      socket
      |> assign(assigns)
      |> assign(:changeset, changeset)
      |> assign(:product, product)
    }
  end

  @impl true
  def handle_event("validate", %{"product" => product_params}, socket) do
    changeset =
      socket.assigns.product
      |> Products.change_product(product_params)
      |> Map.put(:action, :validate)

    {:noreply, assign(socket, :changeset, changeset)}
  end

  def handle_event("save", %{"product" => product_params}, socket) do
    changeset = Products.change_product(%Product{})

    {:noreply, assign(socket, :changeset, changeset)}
  end
end