Conditional Validation in Ecto for OR - 1 of 2 fields is required

前端 未结 3 1350
时光取名叫无心
时光取名叫无心 2021-02-14 02:24

How can I do conditional validation for OR logic, where we check to see if 1 of the 2 values is present or both values are present.

So, for example, if I want to check t

3条回答
  •  温柔的废话
    2021-02-14 03:19

    How about:

      def validate_required_inclusion(changeset, fields,  options \\ []) do
        if Enum.any?(fields, fn(field) -> get_field(changeset, field) end), 
          do: changeset,
          else: add_error(changeset, hd(fields), "One of these fields must be present: #{inspect fields}")
      end
    

    get_field gives you fields accepted by the change set, both changed (cast) and non-changed, and Enum.any? will ensure that at least one of the field is in there.

提交回复
热议问题