CodeIgniter Forums

Full Version: Validation in controllers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I have some general best practices question about how to handle validation. 
As far as my knowledge gets we do form validation in the controller. For example, to check if certain fields are required, max length and etc.
In my practise I have seen that sometimes this validation checks can become quite big.
In those cases I usually separate them the in different private function in the controller so the code can be more readable and to off-load some of the function content.
However I don't feel that having private functions in the controller and chunking the things so much is a good thing and also in terms of reusability can be not so handy to keep them in the controller.

What would you suggest when you have large validation functions?
You can also just grab all the data in the controller, pass them to the model and do the validation in the model. Throw an exception if it's not valid and make your controller catch the exception to display the error in the view. That way you can call the validation function from anywhere in the application.

...or you could create a private method/function that handles only validations. This way your page controllers will stay small.
...or you could create a helper function that handles only validations.
...or you could create a validation library.

You have many options to choose from.
Thank you for the answers.
I have checked all your suggestions. 
For me it seems that the validation should be done in the model and as far as I see that how is also suggested in CI4.

HTML 5 has builtin validation and should alleviate most problems:

HTML5 Attributes

HTML5 added the following attributes for <input>:

height and width
min and max
pattern (regexp)
@John_Betong: That's a HUGE security problem. As people can just delete those from the DOM and submit XSS etc without any issue.

Personally I'm using form validation inside Controllers (with private functions to load my rules), as I'm using multiple models for saving data. So I need to validate it before processing it into my models. If I would do it again from scratch I would put my logic inside a library or extend a controller with those private functions. So that the main controller won't be so bloated.
(09-15-2019, 01:25 AM)jreklund Wrote: [ -> ]@John_Betong: That's a HUGE security problem. As people can just delete those from the DOM and submit XSS etc without any issue.

Exactly! Validation should be done on both side. On the frontend for better user experience (with html5 and javascript) and on the backend for security because you can't trust what is coming from the web, even if you do validation in your form.
In frontend views I use html_escape() with input and textarea.