<.form
for={@form}
phx-change="validate_strict"
phx-submit="save_strict"
>
<.password_input field={@form[:password]} class="password-input">
<:label>Password</:label>
<:visible_indicator><.heroicon name="hero-eye" class="icon" /></:visible_indicator>
<:hidden_indicator><.heroicon name="hero-eye-slash" class="icon" /></:hidden_indicator>
<:error :let={msg}>
<.heroicon name="hero-exclamation-circle" class="icon" />
{msg}
</:error>
</.password_input>
<.action type="submit" class="button button--accent">
Submit
</.action>
</.form>
defmodule MyAppWeb.PasswordInputFormLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
ecto_form =
%MyApp.Forms.PasswordForm{}
|> MyApp.Forms.PasswordForm.changeset_validate(%{})
|> Phoenix.Component.to_form(as: :password_input_ecto, id: "password-input-live-form-ecto")
{:ok, assign(socket, :ecto_form, ecto_form)}
end
def handle_event("validate", %{"password_input_ecto" => params}, socket) do
changeset =
%MyApp.Forms.PasswordForm{}
|> MyApp.Forms.PasswordForm.changeset_validate(params)
|> Map.put(:action, :validate)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :validate,
as: :password_input_ecto,
id: "password-input-live-form-ecto"
)
)}
end
def handle_event("save", %{"password_input_ecto" => params}, socket) do
case MyApp.Forms.PasswordForm.changeset_validate(%MyApp.Forms.PasswordForm{}, params) do
%Ecto.Changeset{valid?: true} = changeset ->
_data = Ecto.Changeset.apply_changes(changeset)
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(
MyApp.Forms.PasswordForm.changeset_validate(%MyApp.Forms.PasswordForm{}, params),
as: :password_input_ecto,
id: "password-input-live-form-ecto"
)
)}
changeset ->
{:noreply,
assign(
socket,
:ecto_form,
Phoenix.Component.to_form(changeset,
action: :insert,
as: :password_input_ecto,
id: "password-input-live-form-ecto"
)
)}
end
end
end
defmodule MyApp.Forms.PasswordForm do
use Ecto.Schema
import Ecto.Changeset
embedded_schema do
field :password, :string, redact: true
end
def changeset(form, attrs \\ %{}) do
form
|> cast(attrs, [:password])
|> validate_required(:password)
end
def changeset_validate(form, attrs \\ %{}) do
form
|> cast(attrs, [:password])
|> validate_required([:password], message: "can't be blank")
|> validate_length(:password, min: 8, message: "must be at least 8 characters")
end
end