Validate_number: comparing two fields

I just quickly adjusted this from an ecto validation I do with dates:

@doc """
Validate two integers being one after another

## Examples

    validate_increasing_order(changeset, :from, :to)
    validate_increasing_order(changeset, :from, :to, allow_equal: true)

"""
def validate_increasing_order(changeset, from, to, opts \\ []) do
  {_, from_value} = fetch_field(changeset, from)
  {_, to_value} = fetch_field(changeset, to)
  allow_equal = Keyword.get(opts, :allow_equal, false)

  if compare(from_value, to_value, allow_equal) do
    changeset
  else
    message = message(opts, "must be smaller then #{to}")
    add_error(changeset, from, message, to_field: to)
  end
end

defp compare(f, t, true), do: f <= t
defp compare(f, t, false), do: f < t
9 Likes