Model Validation Rules - Unexpected behaviour - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28) +--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30) +--- Thread: Model Validation Rules - Unexpected behaviour (/showthread.php?tid=75709) |
Model Validation Rules - Unexpected behaviour - Tysonpower - 03-08-2020 After upgrading from CI4 RC to CI4.02 i had a error while using Model->save() to insert data into the Database. The Problem seems to be that the Validation rules are also used on fields that are not in the Allowed Fields list while saving. I store my validation rules i use for Form Validation in the Model, so in my example i have a passwordrepeat field in the form and Validationrules but NOT in the Entity and Database. When asking Model->errors() it shows the following Error: [passwordrepeat] => The passwordrepeat field is required. When i remove the Validation rule for passwordrepeat in the Model it works all fine. Here are some codesnippets that i created to reproduce the error: Controller Code: public function ci_val_test() Entity Code: <?php namespace App\Entities; Code: use CodeIgniter\Entity; Model Code: <?php namespace App\Models; RE: Model Validation Rules - Unexpected behaviour - includebeer - 03-08-2020 Since passwordrepeat is not a database field, I don’t think it should be validated in the model. The controller seems like a better place for that since you only need to validate that field when you submit the register form. If you look at Myth Auth, that’s how Lonnie made it too: https://github.com/lonnieezell/myth-auth/blob/develop/src/Controllers/AuthController.php#L150 RE: Model Validation Rules - Unexpected behaviour - michalsn - 03-08-2020 @Tysonpower ok, now when I see the whole picture, the issue is obvious and it's your code. You can't expect from validation to be successful when you require a passwordrepeat field and at the same time, you are not passing this variable to the entity/model. If this code was working (no validation errors) with RC, then it was clearly a bug. Data validation shouldn't take into consideration only fields listed in allowedFields because it would lead us to the situation where you "think" something is validated but it isn't in reality. If you want to make it work in this form, then I would propose changing a require rule, to if_exist : Code: 'passwordrepeat' => 'if_exist|min_length[8]|matches[password]' @includebeer I think Lonnie did that in Myth/Auth just because of a practical point of view - you can't expect to have `pass_confirm` field present on every interaction with a model - only on user creation or password change. So I think that was the reason behind validating this data in the controller. |