Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 778
Martinos Avatar asked May 15 '16 16:05

Martinos


People also ask

What is Changeset elixir?

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.

What is ecto elixir?

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.


1 Answers

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")
like image 99
Dogbert Avatar answered Oct 08 '22 00:10

Dogbert