Welcome Guest, Not a member yet? Register   Sign In
Model Validation Rules - Unexpected behaviour
#1

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()
    {
        $userModel = new \App\Models\UserModel();

        $new_user = new \App\Entities\User();
        $new_user->username = 'username';
        $new_user->email = '[email protected]';
        $new_user->password = 'password';

        if($userModel->save($new_user)){
            echo "All Good";
        } else {
            echo "Error occoured: ";
            print_r($userModel->errors());
        }

    }

Entity
Code:
<?php namespace App\Entities;
Code:
use CodeIgniter\Entity;

class User extends Entity
{

    protected $attributes = [
        'user_id' => null,
        'email' => null,
        'password' => null,
        'username' => null,
        'created_at' => null,
        'updated_at' => null,
        'deleted_at' => null,
    ];
}
?>



Model
Code:
<?php namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table         = 'user';
    protected $primaryKey = 'user_id';
    protected $allowedFields = [
        'username', 'email', 'password'
    ];
    protected $returnType    = 'App\Entities\User';
    protected $useTimestamps = false;
    protected $useSoftDeletes = true;
    protected $validationRules = [
        'username'  => 'required|alpha_dash|min_length[3]|is_unique[user.username]',
        'email'  => 'required|valid_email|is_unique[user.email]',
        'password'      => 'required|min_length[8]',
        'passwordrepeat'      => 'required|min_length[8]|matches[password]'             // works if removed, was fine in RC
    ];
}

?>
Reply


Messages In This Thread
Model Validation Rules - Unexpected behaviour - by Tysonpower - 03-08-2020, 12:03 PM



Theme © iAndrew 2016 - Forum software by © MyBB