I want to set an error on an Ecto.Changeset that is not specific to a field.
In my case, I have a login form and I want to set an error saying that either the email or the password is invalid. However I still want to highlight the email
or password
field when they are empty.
In Rails you can do that by adding an entry to errors[:base]
. Is there an equivalent in Ecto ?
Changesets are used for creating and modifying your models. A changeset is literally a struct that stores a set of changes (as well as the validation rules.) You pass a changeset to your Ecto Repo to persist the changes if they are valid.
Ecto is an official Elixir project providing a database wrapper and integrated query language. With Ecto we're able to create migrations, define schemas, insert and update records, and query them. Changesets. In order to insert, update or delete data from the database, Ecto. Repo.
Ecto.Changeset.add_error
allows you to pass any atom as the key, it doesn't have to be a field of that model. You can add the error to :base
like this:
add_error(changeset, :base, "email or password is invalid")
and then in your template, either do:
<%= error_tag f, :base %>
or (after checking if there's an error):
<%= @changeset.errors[:base] %>
Another option for your usecase is to add the error on both :email
and :password
changeset
|> add_error(:email, "email or password is invalid")
|> add_error(:password, "email or password is invalid")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With