How can I do conditional validation for OR logic, where we check to see if 1 of the 2 values is present or both values are present.
So, for example, if I want to check t
Here's a simple way. You can customize it to support better error messages:
def validate_required_inclusion(changeset, fields) do
if Enum.any?(fields, &present?(changeset, &1)) do
changeset
else
# Add the error to the first field only since Ecto requires a field name for each error.
add_error(changeset, hd(fields), "One of these fields must be present: #{inspect fields}")
end
end
def present?(changeset, field) do
value = get_field(changeset, field)
value && value != ""
end
Test with a Post model and |> validate_required_inclusion([:title , :content])
:
iex(1)> Post.changeset(%Post{}, %{})
#Ecto.Changeset, valid?: false>
iex(2)> Post.changeset(%Post{}, %{title: ""})
#Ecto.Changeset, valid?: false>
iex(3)> Post.changeset(%Post{}, %{title: "foo"})
#Ecto.Changeset, valid?: true>
iex(4)> Post.changeset(%Post{}, %{content: ""})
#Ecto.Changeset, valid?: false>
iex(5)> Post.changeset(%Post{}, %{content: "foo"})
#Ecto.Changeset, valid?: true>