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 coming from view and handles displaying errors, etc. From that angle it makes more sense to put it into controllers.

Which one is the right approach from the MVC point of view?

P.S my form validation actually consists only of writing a list of fields, their rules, and passing it on to a form validation library, which returns true/false on whether it passed validation or not.


$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->validate())
    // Process data
    $this->register_form(); //A controller action that will show a view with errors

Should this be put into a controller or model?


I suppose people, who say validation should be done in Controller are from CakePHP-like-world, but I'm from Yii-like-world :) Validation in CakePHP VS Validation in Yii

Written by Nemoden

Different types of validation should be done in different places. Model should not care about if the email field matches the confirm_email field, it just needs the email value. It is not so black and white. Where validation rules are defined and where they run depend on what they apply to. In different instances of the same form (i.e. different views), the rules may change and that is not the Model's job. Example: If you editing a user's profile as an admin, allow fields to be omitted, if you are editing your own profile than we need all fields complete. The same Model will save the data.

Written by Wesley Murch

@Mad If you're editing as admin and want all fields to be omitted, its the controller's job to check that and not call the validation method. Simply not doing the validation will solve that scenario.

Written by Click Upvote

Exactly my point! It's the controller's job to define the rules, exactly what you are doing in your example! Should this be put into a controller or model?

Written by Wesley Murch

@Mad I could just as easily check within the model itself whether the user is logged in as admin or not since my authentication library is available to both controllers & models. That's probably the right way to do it.

Written by Click Upvote

Accepted Answer

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.

Written by Nemoden
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki