CodeIgniter Forums
Validation Class in Controller or Model? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forum-21.html)
+--- Thread: Validation Class in Controller or Model? (/thread-12165.html)



Validation Class in Controller or Model? - El Forum - 10-08-2008

[eluser]chrisco23[/eluser]
Recently I have been refactoring my first CI project which I began 3 years ago.

At the time I did my form validation in my models. I was about to transfer the validation to the controllers this time around but then I started second guessing myself.

I can see an argument that the validation is most closely tied to the form and so it belongs in the controllers, and then I can see the argument that the data is most closely tied to the data models.

I have one rather complex form in particular where the flow will be:
Do some validation, then do some queries, then do some more validation, more queries, etc.

What have others found to be most practical and is it the same as what is the "theoretical" best practice?

I tried Googling around about form validation in MVC and mostly I found that Rails and Cake seem to validate in models.


Thanks,
Chris


Validation Class in Controller or Model? - El Forum - 10-08-2008

[eluser]Colin Williams[/eluser]
There are many ways to look at it, and I have never come down on either side of the fence. Here's my best answer:

Validation is made up of essentially two operations. Defining rules, fields, and values, and then running the validation process and reacting to success and failure. One could argue that rules, fields and values are all tied to the data, so defining those belongs in the model. But the success/error handling is business logic that belongs in the controller. So, you could simply add get_field(), get_rules() get_values() methods to your models, which the controller obtains and passes in to the Validation class. That seems like the best way to split the process.

However, I've yet to encounter a situation where I have two controllers that process the same exact form for the same exact object. So, abstracting it out via the model has never seemed necessary, so I do it all in the controller. And remember, too, that validation and prepping are two different things. Your models should always be responsible for prepping data before insertion. That is to say, your model functions should be extremely flexible as to what they accept, which can make for more friendly API. (An example would be a tagging system. The model should accept a comma delimited string of tags that it then translates into an array that it can process and add to the database. No reason for the controller to do this.)