Ash FrameworkAF
Ash Framework5mo ago
6 replies
stefantree3

Conditionally run validations

Hey

I have a UserFeedback resource that has questions & answers collected from users who provide feedback in my LiveView app via a create :provide_feeback action

When determining whether to get feedback from a user I check if the changeset is valid, i.e. Ash.Changeset.for_create(UserFeedback, :provide_feedback, %{...}, actor: current_user).valid?
When a user if providing feedback, I also validate on change of the form:
  @impl true
  def handle_event("change", %{"form" => params}, %{assigns: %{form: form}} = socket) do
    form = form |> Form.validate(params, errors: form.submitted_once?)

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


This allows me to encapsulate all of the validation logic in the action itself, being:
* User must not have already provided feedback (i.e. UserFeedback with user_id == current_user.id doesn't exist)
* The answer to each question must be less than a configured number of characters

I don't really want to be checking the db for an existing UserFeedback on each keypress when the user is filling out the form, just initially when determining whether to show the form and then when submitting it

I could provide an argument, say: validate_full? and if false then skip the existence check

Since this pattern might be useful across several actions for the same reason, I wonder if there's a better way to do this or would it be valuable to add?

Thanks!
Was this page helpful?