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

后端 未结 10 874
生来不讨喜
生来不讨喜 2020-12-25 07:52

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
10条回答
  •  悲哀的现实
    2020-12-25 08:50

    This is interesting. For the longest time I performed all validation in the model, right above what I would consider DAL (data access layer). My models are typically pattern'ed after table data gateway with a DAL providing the abstraction and low level API.

    In side the TDG I would implement the business logic and validations, such as:

    1. Is username empty
    2. Is username > 30 characters
    3. If record doesn't exist, return error

    As my application grew in complexity I began to realize that much of the validation could be done on the client side, using JavaScript. So I refactored most of the validation logic into JS and cleanuped up my models.

    Then I realized that server side validation (not filtering/escaping -- which I consider different) should probalby be done in the server as well and only client side as icing on the cake.

    So back the validation logic went, when I realized again, that there was probably a distinct difference between INPUT validation/assertion and business rules/logic.

    Basically if it can be done in the client side of the application (using JS) I consider this to be INPUT validation...if it MUST be done by the model (does this record already exist, etc?) then I would consider that business logic. Whats confusing is they both protecte the integrity of the data model.

    If you dont' validate the length of a username then whats to stop people from creating a single character username?

    I still have not entirely decided where to put that logic next, I think it really depends on what you favour more, thin controllers, heavy models, or visa-versa...

    Controllers in my case tend to be far more application centric, whereas models if crafted carefully I can often reuse in "other" projects not just internally, so I prefer keeping models light weight and controllers on the heavier side.

    What forces drive you in either direction are really personal opinion, requirements, experiences, etc...

    Interesting subject :)

提交回复
热议问题