From 1f53222e3246a751ed0872d7fe5e630cb56bdb5b Mon Sep 17 00:00:00 2001 From: Martin Nijboer Date: Wed, 20 Nov 2024 22:00:25 +0100 Subject: [PATCH] Check item rules for array maps without properties --- lib/goal.ex | 8 +++++++- test/goal_test.exs | 22 +++++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/goal.ex b/lib/goal.ex index 7ddde3f..dfc5356 100644 --- a/lib/goal.ex +++ b/lib/goal.ex @@ -933,7 +933,13 @@ defmodule Goal do |> put_in([Access.key(:changes), Access.key(field)], Enum.reverse(changesets)) |> Map.update!(:valid?, &Kernel.&&(&1, valid?)) else - changeset + item_rules = Keyword.get(rules, :rules) + + if item_rules do + validate_fields(item_rules, field, changeset) + else + changeset + end end end diff --git a/test/goal_test.exs b/test/goal_test.exs index 995715d..1b78242 100644 --- a/test/goal_test.exs +++ b/test/goal_test.exs @@ -1126,9 +1126,7 @@ defmodule GoalTest do ] } - schema = %{ - list: [type: {:array, :map}] - } + schema = %{list: [type: {:array, :map}]} changeset = Goal.build_changeset(schema, data) @@ -1163,6 +1161,24 @@ defmodule GoalTest do } end + test "list of maps, min and max" do + schema = %{ + list: [ + type: {:array, :map}, + rules: [min: 1, max: 1] + ] + } + + data_1 = %{"list" => []} + data_2 = %{"list" => [%{"hello" => "world"}, %{"hello" => "world"}]} + + changeset_1 = Goal.build_changeset(schema, data_1) + changeset_2 = Goal.build_changeset(schema, data_2) + + assert errors_on(changeset_1) == %{list: ["should have at least 1 item(s)"]} + assert errors_on(changeset_2) == %{list: ["should have at most 1 item(s)"]} + end + test "list of maps, invalid type given" do schema = %{ list: [