Search code examples
elixirphoenix-frameworkecto

How to add a global error to an Ecto Changeset


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 ?


Solution

  • 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")