When to use check constraints vs validators?

In a phoenix project let’s say I have a user model. I wan’t to ensure the registered user is over 16 years old. I have a field in the form to collect the birth date. With that value I believe there are three options

  • Validate using changeset:
    • PRO: No unnecessary database transaction
    • CON: If the bad data reaches the database it get’s stored
  • Validate using check constraints:
    • PRO: No invalid data in the database
    • CON: Increased unnecessary database hits
  • Validate both in code and in the database:
    • PRO:
      • Minimizes database hits
      • Ensures data integrity
    • CON:
      • Duplicate logic (triple if client side validation is taken into account)
      • Wasted computing power and time

So what is the proper strategy in these cases? I would go with both changeset and constraints but I would like to know opinions from more experienced devs. Is there any fourth option?


If I can put a constraint in the database for something, then I do. That way I never have to worry about bad data.

Putting a constraint in the database still means you have to handle that constraint in your changeset, so it is there regardless. :slight_smile: