[PROPOSAL] Validate existing fields

30 views
Skip to first unread message

Rory Hodgson

unread,
Jun 16, 2023, 4:40:55 PM6/16/23
to elixir-ecto
Hi,

I searched around on github, elixir forums and here, and I don't see anything mentioning this, so apologies if it's been mentioned before, because it feels like something someone has probably asked before...

Bottom line: can we validate existing fields when changing a different field?

We have a schema in our codebase that represents something, and it has a 'status' on it. We have a series of function heads that match on the 'status' field, after having performed a `get_field` on the changeset.

So, something like:
`check_status(changeset) do
  status = get_field(changeset, :status)
  check_status(changeset, status)
end

check_status(changeset, :some_status), do: blah_blah_blah
check_status(changeset, :some_other_status), do: blah_blah_blah`

So far it's worked pretty well, doing validations in here, because the only validations we've performed are `validate_required`.

I didn't realise, however, that all other validations only work on changes. I was wondering if there's a way we could change `validate_number` and other such validations to take in a `on_change` keyword or something, so that they don't look at changes but at existing fields instead?

I think there's probably a reason this doesn't happen. One thing that makes me think this is, well, I can't be the only person who's ever wanted to call validations on existing fields, and not just changes. The other reason is that I spent an hour or so spiking this, trying to see how you might implement it, and immediately ran into hurdles with trying to get the field. If it's a change, all the changes are neatly mapped for ease of accessibility. To validate just any old field, it'd have to be flexible enough to somehow traverse all the fields in a nested `changeset.data` map, and somehow know it's looking at the right field on the right thing in that tree... which is er... yeah, unless I'm missing something, that's not simple.

At the end of the day, Changesets are about changes so it makes sense that what they validate is what has changed really. But if I'm looking at the wrong thing, could you please point me towards the proper way to handle this sort of thing then? I know I could just do a validation at the level that calls the changeset, but given all my other validation is in the schema, it would be nice to keep it there. At this point I'm just gonna write my own custom validation function that just does `get_field` and checks the value.

If none of this is possible, could whoever manages the HexDocs please update them to clarify that `validate_number` and other such validations are only performed on changes? I re-read the docs a few times and don't see it in there, but maybe I'm missing something?

Thanks,

Rory
Reply all
Reply to author
Forward
0 new messages