Hey, guys. If anyone knows, I’d appreciate the help
I need a user to enter 3 numbers but I need to validate the following, which I don’t how to:
-
- The sum of these 3 numbers must be 100
-
- The numbers must be positive
This is what I have at the moment and I’m totally lost. I’ve done a lot of research but nothing enlights me.
My schema:
alias Numbers, as: N
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "transportation_schemas" do
field :using_own, :decimal, default: 0
field :using_provider, :decimal, default: 0
field :using_third, :decimal, default: 0
timestamps()
end
My changeset:
def changeset(transportation_schema, attrs) do
transportation_schema
|> cast(attrs, [:using_own, :using_provider, :using_third])
|> validate_required([:using_own, :using_provider, :using_third])
|> validate_percentage()
end
And this is the function that validates the sum:
defp validate_percentage(changeset) do
using_own = get_field(changeset, :using_own)
using_provider = get_field(changeset, :using_provider)
using_third = get_field(changeset, :using_third)
sum = N.add(using_own, using_provider) |> N.add(using_third)
IO.puts(sum)
if sum < 100 do
add_error(changeset, :using_own, "less")
end
end
I understand that the line: add_error(changeset, :using_own, "less")
is totally wrong because I don’t need a field but the result of a sum. I don’t know if add_error
even solves the problem.
I just looking for something like “Error. Your values don’t sum 100”
And as far the positive numbers I have no idea how to
Hopefully anyone as done something similar