Created
July 17, 2020 23:45
-
-
Save noelworden/475777894740ebb8c1ac015cadf23d58 to your computer and use it in GitHub Desktop.
#blog_snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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