Ecto validate existing record

Hi,

how to validate existing records against changeset validations? Looking for best solution.

Imagine changing validation conditions and now i need to validate existing record in database using same validation rules. Ecto seems to run validations only on changes.

eg database has %User{name: "Joe"}


new validate length value name min: 5

def changeset(user, attrs) do
  ..
  |> validate_length(:name, min: 5, max: 100)
end


User.changeset(user, %{}) says its valid
User.changeset(user, %{name: "Joe"}) says its valid


Use an empty User struct and your user from the db as attrs (might need to turn it into a map first)?

Yes, Ecto changesets are primarily concerned about changes and the repo will apply partial updates.

So if you want to re-validate data, I think you’ll need to do it manually with something like:

attrs = Map.from_struct(user)

user
|> cast(attrs, [...])
|> validate_length(:name, min: 5, max: 100)
...
1 Like