Validates not nil of fields only when they exist

I want to validate not nil of fields only when they exist.

ex)

defmodule User do
  schema "users" do
    field(:email, :string)
    field(:name, :string)
    field(:phone, :string)
  end

  def new_changeset(user, attrs) do
    user
    |> cast(attrs, [:email])
    |> validate_required([:email])
  end

  def update_changeset(user, attrs) do
    user
    |> cast(attrs, [:name, :phone])
    |> validate_required([:name, :phone])
  end
end

{:ok, user} =
  %User{}
  |> User.new_changeset(%{email: "hi@good.com"})
  |> MyRepo.insert()

user
|> User.update_changeset(%{name: "json"})
|> MyRepo.update()
=>
{:error,
 #Ecto.Changeset<
   action: :update,
   changes: %{name: "json"},
   errors: [phone: {"can't be blank", [validation: :required]}],
   data: #User<>,
   valid?: false
 >}

I used validate_required to prevent nil input like %{name: nil}.

How can I prevent nil input and solve the can’t be blank error simultaneously?

1 Like
validate_change(changeset, :phone, fn 
  _, nil -> [phone: "can't be blank"]
  _, _ -> []
end)
4 Likes