Ash FrameworkAF
Ash Framework3y ago
9 replies
Blibs

Best way to process a field in a form changeset before validation

In my form, I have a
price
field which uses a JS hook to format it in a nicer way to the user.

For example, if the user types 23432, it will display in the input element 23,432.00

The problem that I'm having is that if I send that value to be validated with AshPhoenix.Form.validate, it will fail since 23,432.00 is not a valid decimal, so what I do is run this in the params before the validation:

  defp maybe_process_price(%{"price" => ""} = params), do: params

  defp maybe_process_price(%{"price" => price} = params) when is_binary(price) do
    price = price |> Money.parse!(:USD) |> Money.to_string(symbol: false, separator: "")

    %{params | "price" => price}
  end


That way I first revert the price to 23432 and then send to validate. That works, but now LiveView will update my input with the value 23432 removing the correct 23,432.00.

Since I can't find a reliable way to handle that from the LiveView side, I was wondering if there is a good way to add a step to my action so it will do that transformation for that field before validating the changeset?

I tried using change, but that doesn't seem to work since I guess that will only run when the action is actually running, not during changeset validation.
Was this page helpful?