Best way to do validation

Hello.

How would you validate the data saved to a model? Inside a model? A seperate validation file or a form validation?

And why, i was thinking to do it inside a model, but then the model would be pretty large.

Do you guys have any experience ?

edited 17d ago

Personally I would use a Form

https://docs.phalcon.io/4.0/en/forms

Create the form and add the elements you need there. Also add the necessary validators in the form itself. When you receive the input you can validate your form and that will return true or you will have messages for validators that failed.

You can then use something like this:

$customer = Customers::findFirst($customerId);
$form     = new CustomerForm($customer);

$form->bind($_POST, $customer);

if (false !== $form->isValid()) {
    $customer->save();
}

If that does not validate you have errors. If it does validate you will save the model directly. Note that the form elements need to have the same names as the elements in your model. If you want to obscure this, then ou will need to pass the $_POST in your isValid and if everything is OK you will be able to get the data from the request, sanitize it and save it to your model.

Using the form and bind allows you to have validators on the form itself and also attach filters which will allow you to ensure your data has the correct case and sanitizations.



295

One thing that I dont like about forms, is that i migth dublicate some rules

For example signup user, and user settings, have some of the same rules and if i go change one rule, then i need to change it in multiple files?

edited 17d ago

It depends, i like in models more, because then im certain that no matter where i do save i always have correct, validated model.

Though if you are using phalcon forms then store it there.



295
edited 17d ago

I was thinking to use Phalcon models too, becuase of the of the same reason as Wojciech Ślawski. But, the form has the function "addValidators", which gives it a better structure.

Add another vote for puting the validation in the model. And also for the same reasons - the same validation will be done regardless of the context in which the model is being used.

Also, I think it's MVC best practice to put validation like this in the model. The model is the only entity that should know the inner workings of the model - which includes what makes valid data.