MVC Question: Should I put form validation rules in the controller or model?

前端 未结 9 1603
野性不改
野性不改 2020-12-12 14:41

On one hand form validation could be seen as part of the application logic and therefore belonging in the model.

On the other hand, it deals directly with the input

相关标签:
9条回答
  • 2020-12-12 15:39

    Validation is Model's issue. Only model knows how your data should look like. You describe your data fields in model, so you should describe validation rules for this fields in the same place.

    It seems to be obvious for me, but I'd gladly listen to opponents.

    0 讨论(0)
  • 2020-12-12 15:41

    I would say the form validation code should be in the controller (not the model) in most cases.

    Madmartigan put it best in his comment above "Form validation !== Data validation. Not all forms interact with a model"

    Web forms are logically part of the View/Controller part of MVC, since the user interacts with them in the view.

    0 讨论(0)
  • 2020-12-12 15:44

    Ideally, you want 3 layers of validation:

    1. View: Client side (javascript, html5 validation, etc.). This catches obvious errors and omissions before the data hits the controller, wasting the user's time and invoking an unnecessary page load if there are errors.
    2. Controller: This is your Form validation layer. Controllers usually are meant to handle input directly, and send it over to the model. It is very rare that every field in your form has a directly related column in your DB, you usually need to alter the data in some way before passing it to the model. Just because you have a field you need to validate called "confirm email", doesn't mean that your model will be dealing with a "confirm email" value. Sometimes, this will be the final validation step.
    3. Model: This is your last line of defense for validation, and possibly your only validation in the case of sending data to the model without it coming directly from a form post. There are many times when you need to send data to the DB from a controller call, or with data that is not user input. We don't want to see DB errors, we want to see errors thrown by the app itself. Models typically should not be dealing with $_POST data or user input directly, they should be receiving data from the controller. You don't want to be dealing with useless data here like the email confirmation.
    0 讨论(0)
提交回复
热议问题