Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you do your validation? model, controller or view

Where do you put user input validation in a web form application?

  1. View: JavaScript client side
  2. Controller: Server side language (C#...)
  3. Model: Database (stored procedures or dependencies)

I think there is validation required by each level:

  1. Did the user input a sane value
    • are dates actual dates, are numbers actualy numbers ...
  2. Do all of the checks in 1. again plus checks for malicious attacks(IE XSS or SQL injection)
    • The checks done in 1. are mainly to avoid a server round trip when the user makes a mistake.
    • Since they are done on the client side in javascript, you can't trust that they were run. Validating these values again will stop some malicious attacks.
  3. Are dependencies met (ie. did the user add a comment to a valid question)
    • A good interface makes these very hard to violate. If something is caught here, something went very wrong.

[inspired by this response]

like image 393
alumb Avatar asked Sep 25 '08 16:09

alumb


2 Answers

I check in all tiers, but I'd like to note a validation trick that I use.

I validate in the database layer, proper constraints on your model will provide automatic data integrity validation.

This is an art that seems to be lost on most web programmers.

like image 154
FlySwat Avatar answered Oct 04 '22 18:10

FlySwat


Validation in the model, optionally automated routines in the UI that take their hints from the model and improve the user experience.

By automated routines I mean that there shouldn't be any per-model validation code in the user interface. If you have a library of validation methods, such as RoR's (which has methods like validates_presence_of :username) the controller or view should be able to read these and apply equivalent javascript (or whatever is convenient) methods.

That means you will have to duplicate the complete validation library in the ui, or at least provide a mapping if you use a preexisting one. But once that's done you won't have to write any validation logic outside the model.

like image 34
Matthias Winkelmann Avatar answered Oct 04 '22 19:10

Matthias Winkelmann