How to add a global bug to the Ecto changeset

I want to set an error in Ecto.Changeset that is not field related.

In my case, I have a login form, and I want to fix the error by indicating that either the email address or password is invalid. However, I still want to highlight the email or password field when they are empty.

In Rails, you can do this by adding an entry to errors[:base] . Is there an equivalent in ecto?

+5
source share
1 answer

Ecto.Changeset.add_error allows Ecto.Changeset.add_error to pass any atom as a key, it does not have to be a field of this model. You can add an error to :base as follows:

 add_error(changeset, :base, "email or password is invalid") 

and then in your template follow these steps:

 <%= error_tag f, :base %> 

or (after checking for an error):

 <%= @changeset.errors[:base] %> 

Another option for your use is to add an error on both :email and :password

 changeset |> add_error(:email, "email or password is invalid") |> add_error(:password, "email or password is invalid") 
+11
source

All Articles