Liveview Form Validation 2 Changesets

I have a form that has 3 inputs that are all defined in a schema (Event), use the helper functions like the liveview generator outputs and are validated via a handle_event “validate” function via a single changeset.

For creating a new Event in addition to these 3 inputs defined in the schema I would like to include an addition input field that allows users to enter an area code, which I would like to be able to validate (3 numbers, certain ones are valid, etc) and then pass to the create_event function in my context.

So far by making an input field I am able to capture an entered area code and throw the entered code into the event_params to then be passed into the create_event function. However by doing this the input field isnt being validated like the other 3 inputs.

I am still pretty new to liveview, points in terms of how to accomplish this would be helpful. I was playing around with making area_code a virtual attribute in the Event schema so I can add a changeset and do it as part of the form (now all 4 inputs are connected to 1 schema), does that seem like the right direction?

I’m not completely sure I understood your issue.

You’ve got an Event schema that you can Create and Update using the same form.
When Creating you validate 4 fields, when Updating you validate only 3.

Do you use different changesets for creation/update?

You may be able to do something like this:

  def handle_event("validate", %{"event" => event_params}, socket) do
    changeset =
      if event_params["additional_field"] do
        |> Event.create_changeset(event_params)
        |> Map.put(:action, :validate)
        |> Event.update_changeset(event_params)
        |> Map.put(:action, :validate)

    {:noreply, assign(socket, :changeset, changeset)}

(This is a very simple snippet so you can get the gist of it. You can improve it by using pattern match)

Is this what you are looking for?

Yes that helps a lot. Sometimes I get thrown off as I haven’t been doing validation via live view but it’s not magic just in that function!