I'm using Kohana, but I think this question is more general.
I have been doing form validation in the controller, and it has worked well so far. But lately, I've ran into a problem.
I have a comments model, and I send comments from a few different controllers to it. Instead of having a validator in every controller, I placed it in the model.
This is great because
This sucks because
ON SUCCESS
array('success' => true);
ON FAIL
array('success' => false, $errors);
I can't help but think this is wrong. It feels wrong.
If I do it in the controller, I can simply do
if ($post->validate()) {
doWhatever();
} else {
$this->template->formErrors = $post->errors('form_errors');
}
Which seems better (to me).
Is there a better way to do this? Should I validate in the controller or method? Am I going crazy?
I don't think all validation rules can go inside the model. Validation is all about the form (or the API). The fact is that when you are validating your data, most of the things depend on the context.
For example, is this a logged-in user taking the action? You wouldn't couple your authentication layer with the model being validated. So, all the checks must go inside the controller. The model is context-agnostic; the form "belongs" to the controller and is context-aware.
I think that having per-form validation rules plus basic in-model checks for well-formed data is the way to go. If you're calling Auth::instance() or Session::instance() inside your model's validate() function, then you're doing it wrong.
I honestly don't see anything wrong with your method, alex. It seems like you're doing it properly. You're following the DRY principle, which for me is usually the yardstick to measure if I'm doing something right when it comes to MVC.
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