#Phoenix LiveView form validation w/ Ecto.Changeset

2 messages · Page 1 of 1 (latest)

cloud pasture
#

I might bang my head against the wall...
Is there any easier approach? Especially the calls to apply_action/2

def handle_event("login", login_params, socket) do
    case Ecto.Changeset.apply_action(Login.changeset(%Login{}, login_params), :create) do
      {:ok, %Login{email: email, password: raw_password} = login_data} ->
        hashed_password = Security.hash_password(raw_password)

        case Repo.get_by(User, email: email, password_hash: hashed_password) do
          nil ->
            {:error, changeset} =
              login_data
              |> Login.changeset()
              |> Ecto.Changeset.add_error(:email, "user does not exists")
              |> Ecto.Changeset.apply_action(:validate)

            updated_socket =
              assign(socket, form: to_form(changeset))

            {:noreply, updated_socket}

          %User{} = found_user ->
            updated_socket =
              socket
              |> assign(current_user: found_user)
              |> redirect(to: ~p"/")

            {:noreply, updated_socket}
        end

      {:error, changeset} ->
        updated_socket =
          assign(socket, form: to_form(changeset))

        {:noreply, updated_socket}
    end
  end

defmodule LoggixWeb.Auth.Login do
  @moduledoc false

  use Ecto.Schema

  import Ecto.Changeset

  @required_fields ~w(email password)a

  @mail_regex ~r/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/

  @primary_key false

  embedded_schema do
    field :email, :string
    field :password, :string
  end

  def changeset(entity_or_changeset \\ %__MODULE__{}, params \\ %{}) do
    entity_or_changeset
    |> cast(params, @required_fields)
    |> validate_required(@required_fields)
    |> validate_email(:email)
  end

  defp validate_email(changeset, field) do
    validate_format(changeset, field, @mail_regex)
  end
end
cloud pasture
#

I also dont see, why the to_form/1 helper function cannot return the correct "response" when the Changeset is fully validated - does someone have a reason for this?