Changeset Validation: Should I use validate_subset when the array to be validated can be empty?

Alright, so I’m quite new to the Elixir universe, so if I’m overlooking anything obvious, please tell me.

I’m trying to validate if a user has a certain role to check if they are allowed to execute the current query. (This will also checked in the frontend but I also want to make sure the api endpoint is not misused).

So, the user can have a set of roles that I get as an array, e.g. [“Role1”, “Role2”, “Role3”] but could also be empty if they are a normal user with no special roles at all.

In my Ecto Schema, I have a virtual filed “roles” where I save said array. Now I thought I could validate it with validate_subset( changeset, :roles, [“TheAllowedRole”, “TheOtherAllowedRole”]) which works great if my array has entries. But if it is empty, it doesn’t throw an validation error which is not what I would expect.

My immediate thought is to use an additional validate_length with min 1 entry. Is this the best procedure or did I do something wrong or would you recommend using another method all together?

Thank you for your help! :smiley:

You’d usually use validate_required to make sure fields are actually filled in. All other validations only validate if there are actually changes.