DEV Community


Sequalize model validation or express-validator?

・1 min read


I am writing an api with Sequelize for the first time. I am stuck on thinking what the best way is to validate body parameters. On one hand, Sequelize provides pretty extensive model validation but I need to attempt to save the model in order to get validation error, which seems slower and less performant than if I validated the body as the first thing in my route handler with package such as express-validator e.g. Have anyone got any opinions of that?

Discussion (5)

dmfay profile image
Dian Fay

It's good to validate quickly so you can return easy-to-catch errors to the user with a minimum of waiting, and express-validator or any of several other packages will do that perfectly well. But there's one important thing to remember: only the database can truly enforce validation rules. A validation rule in application code is akin to saying "it'd be nice if that field had something in it". If you want to make sure the field has something in it no matter what, set NOT NULL and add a CHECK constraint (unless you're using MySQL <8, which ignores the latter).

For your situation, Sequelize model validation sounds like the worst of both worlds: slower than early checks, not actually enforced by the database.

adrian110288 profile image
Adrian Author

Thank you :) I will then move my validation rule checking into a route handler itself and have actual SQL table constraints as a safety net to be absolutely sure my tables don't take undesirable values.

igeligel profile image
Kevin Peters

Always validate and catch errors as early as possible.

There are two reasons. One is performance but which is not as important as I think.

The other reason is separation. If you validate early you can easily exchange the ORM in this case. It gives you a more dynamic workflow for the future which is good.

adrian110288 profile image
Adrian Author

Thanks Kevin for the answer. I am of the same mindset that I should validate user input before anything else. Would you then say that I should have just a basic validators in the models or should I just not utilize Sequelize validation at all? My only concern is that I would be duplicating validation rules across models and in the route handler. What would be your solution? Thanks

gperezlz profile image
Gastón Perez

Did you solve your question? How could he solve it? I find myself in the same situation.

Forem Open with the Forem app