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.
Example:
$this->load->library('form_validation'); $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 else $this->register_form(); //A controller action that will show a view with errors
Should this be put into a controller or model?
If you're validating data on server side, And your validation does not require application business logic (i.e you're not checking to see if the user has enough credit in his account), You should validate in the controller.
Validation should be in the domain layer, but it can also be used in other layers, like the UI (probably in the Controller or the View in Js) to give fast feedback to the user.
Ideally, you want 3 layers of validation:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With