Skip to content

Instantly share code, notes, and snippets.

@noelworden
Created July 17, 2020 23:45
#blog_snippets
def validate(changeset) do
changeset
|> validate_required([:revenue, :expense, :net_gain, :first_name])
|> mathematical_validation()
|> validate_format(:reference_id, ~r/(^\d+$|\p{L})/u,
message: "must be a number or contain a letter"
)
end
defp mathematical_validation(changeset) do
revenue = get_field(changeset, :revenue)
expense = get_field(changeset, :expense)
net_gain = get_field(changeset, :net_gain)
with {:is_valid, true} <- {:is_valid, changeset.valid?},
{:math_validation, true} <-
{:math_validation, Decimal.sub(revenue, expense) == Decimal.new(net_gain)} do
changeset
else
{:is_valid, false} ->
changeset
{:math_validation, false} ->
add_error(changeset, :net_gain, "must equal revenue minus expense")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment