humdinger
humdinger

Reputation: 531

Ecto: Two unique fields

I've created two unique indexes on fields in the same table, and want to validate them using unique_constraint/3, however, the error message on the front-end only displays for either field, not both if they are not unique. How can I make both errors show up if neither field is unique?

Upvotes: 0

Views: 921

Answers (1)

Mike Buhot
Mike Buhot

Reputation: 4885

You can use Changeset.unsafe_validate_unique/4 to find all the unique validation errors and report them to the user. unique_constraint must also be used to handle potential race condition of the data changing before the new record is inserted.

changeset
|> unsafe_validate_unique([:email], MyApp.Repo, message: "email is already in use")
|> unsafe_validate_unique([:phone], MyApp.Repo, message: "phone number is already registered")
|> unique_constraint(:email)
|> unique_constraint(:phone)

Upvotes: 1

Related Questions