javascript - Where should you validate/sanitize data? -


i building traditional mvc app. have /lib folder defines functions deal database operations , dealing external apis. when processing user input, should validate data? should validate in route controllers , send validated data database functions? or should no validation in route controllers , have functions in /lib folder validation?

for me natural place in model because contains data. grasp expert principle says should assign responsibilities object has information fulfill them.

we argue controller may have information (data) required validation me controllers should light. moreover, think "all information" means not having data must validate, knowing format, , that's model's concern. controller may know how data model needs should be, model used outside controller scope, should not rely on controller's validation work model (almost) last chance detect invalid data (you can, , must, on database, data should validated , sanitised before goes it, although there's direct match between database schema , validation should in model).

every time crud operations model need validate data , ensuring data correct. moreover, controller change data goes model, if controller validated previously, may produce invalid data.

however, think that. controller may change data , in fact lot of time so. unusual have direct map between fields in form , model , have inputs have nothing or little model, should validate them outside model. example, think "repeat password" field. has nothing model! "password" field should reach it.

other people prefer anemic models , may fit best rich models in scenarios, have drawbacks , rich ones fit best in general.

you should consider having validation in client side (i.e. js) can give him fast feedback doing instead of sending data server validated , wait response or load whole page again!

one way use regex because have similar expressions between different languages using, although more not won't enough. or better, use js everywhere node.js , totally forget problem.

this may not answer looking for, there not 1 right way validation different each application. times, validation should occur in different places, doing same validation in different layers of application , different validation between others.

there more questions topic on stackoverflow, check them have different opinions other people: