Validate form fields only when its been focus/change once

Is there a way to validate fields only if its been focus or its value has change once. Currently using embedded schema and changeset to validate the fields on my liveview component.

Validation is working fine but if I change one field, it also validate the other fields which I don’t like.

# Form component
<%= f = form_for @changeset, "#", [phx_change: :validate, phx_submit: :create_game] %>
    <div class="control bottom-gap">
        <%= text_input f, :room_name, class: "input", phx_debounce: "blur", placeholder: "Enter room name" %>
        <%= error_tag f, :room_name %>
    </div>
    <div class="control bottom-gap">
        <%= number_input f, :room_slots, phx_debounce: "blur", placeholder: "Enter number of players (Max of 4)" %>
        <%= error_tag f, :room_slots %>
    </div>
    <div class="control bottom-gap">
        <%= submit "Create", class: "button is-success is-fullwidth", phx_disable_with: "Saving..." %>
    </div>
</form>

Then I have my handle event for the validation:

  def handle_event("validate", %{"create_game_form" => params}, socket) do
    changeset = %CreateGameForm{} |> GameManager.change_game(params) |> Map.put(:action, :insert)
    {:noreply, assign(socket, changeset: changeset)}
  end

I think what I want to do is not yet supported in LiveView, just asking for confirmation or alternatives.

Thank you.

Its is actually supported in LiveView. I have an example here:
https://fullstackphoenix.com/tutorials/form-validation-with-phoenix-liveview

Look close to the end where I edit:

def error_tag(form, field) do
4 Likes

I assume things have changed in LiveView since the post above, but for anyone else wondering about this, see https://hexdocs.pm/phoenix_live_view/form-bindings.html#phx-feedback-for for the official doc on how to make this work now.

5 Likes