Where to put user's input validation

Where to put user's input validation
0

#1

So, I am using some sort of MVC pattern and in my app I have model and controller modules. Model module takes care about all CRUD operations with database. And controller module basically provides middlewares for handling client requests and it also uses model methods. So where should I put input validation? In model or controller?


#2

To my knowledge you would put it in the view-layer, that’s how a framework like react works.

There’s also just plain old HTML validation as well for forms, that uses special attr tags.

Check it out here http://youmightnotneedjs.com/#form_validation


#3

I did html form validations on a client, though only basic ones like <input type='text' />.
But shouldn’t we always validate inputs on server because as we know, we should not trust anybody :question:

I kinda feel I should validate those inputs as early as possible after they arrive to server. And if that’s the case, I think I should do validation in controller and leave model methods pure.

What’s your opinion? :confused:

P.S. Thanks for the link, I wasn’t aware of those special attributes.


#4

You should validate input both on the server and client side.

Validating on the client side ensures the user actually puts in an email address, for instance. But, a user could still just bypass client-side validation, and enter whatever they want in the console. This leaves you open to exploits like SQL injections / bad data entry.

MVC pattern is kind of loosely defined, because we can talk about a MVC frontend and a seperate MVC backend.

But for me I would do the following:

  1. Use the formvalidation in plain HTML with that link above for frontend. It’s good enough for most cases and simple
  2. On backend, the validation should be in the controller or model. It depends how your app is set up though. But from what I’ve seen, its in the controller usually.

I would use this simple backend as an example for the MVC structure (it uses nodeJS and express). It’s a todo app