Where can I store common custom validations?

ecto
changesets
validation
#1

I have custom validation validate_required_inclusion and I want to use it for different contexts. Where can I store such validations?
lib/my_project/commentary/comment.ex

def changeset(%Comment{} = comment, attrs) do
    comment
    ...
    |> validate_required_inclusion([:body, :sticker_id])
  end

  def validate_required_inclusion(changeset, fields) do
    case Enum.any?(fields, fn field -> get_change(changeset, field) end) do
      true ->
        changeset
      false ->
        add_error(changeset, hd(fields), "One of these fields must be present: #{inspect(fields)}")
    end
  end
0 Likes

#2

Put it in a module and place it where it makes sense. Use it in the schemas where you need the validations. There’s nothing special about those functions or ecto, which you’d need to care for.

3 Likes

#3

you also to use validate_change ( https://hexdocs.pm/ecto/Ecto.Changeset.html#validate_change/3 )

There is a reference in this post Validates not nil of fields only when they exist

0 Likes