为什么我的CodeIgniter4 Model ValidationRules不起作用?

iyfjxgzm  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(96)

Codeigniter app/Models/XXXModels.php验证规则不起作用。
我的模型文件是:

<?php

namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'user';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = \App\Entities\User::class;
    protected $useSoftDeletes   = true;
    protected $allowedFields    = ['account','email','phone','password','pwd'];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created';
    protected $updatedField  = 'modified';
    protected $deletedField  = 'deleted';

    // Validation
    protected $validationRules    = [
        'email'        => 'required|valid_email|is_unique[user.email]',
        'phone'        => 'required|is_unique[user.phone]',
        'password'     => 'required|min_length[8]',

    ];
    //protected $fieldValidationMessage= [
    protected $validationMessages= [
        'email' => [ 'is_unique' => 'email exists'],
        'phone' => ['is_unique' => 'phone exists'],
        'password' => ['is_unique' => 'length need > 8']
    ];
    protected $skipValidation       = false;
    protected $cleanValidationRules = false;
    protected $allowCallbacks = true;
    // Callbacks
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

如果用户电子邮件或电话已存在的数据库错误在日志代码一样

$user = new \App\Entities\User(['account' => 'lman','email' => 'lman@lman','phone'=>'000000000','password'=>'123456']);
$upd =  $userModel->save($user);

日志中的错误。

ERROR - 2023-05-24 06:25:42 --\> mysqli_sql_exception: Duplicate entry 'lman@lman' for key 'email' in /{SYSTEMPATH}/api/system/Database/MySQLi/Connection.php:295

所以validationRules不起作用,var_dump模型

\["validationRules":protected\]=\>
array(0) {
}

use setValidationRules正在工作。
如何在初始化文件中使用模型验证规则?

ua4mk5z4

ua4mk5z41#

验证规则消息

//protected $fieldValidationMessage= [
protected $validationMessages= [
    'email' => [ 'required' => 'email required', 'is_unique' => 'email exists'],
    'phone' => ['required' => 'phone required', 'is_unique' => 'phone exists'],
    'password' => ['required' => 'password required', 'min_length' => 'min 8 length']
];

在控制器中设置验证规则use App\Models\UserModel

$userModel = new UserModel();

$this->validate($userModel->validationRules);

// same way set valudation messages

//run validation check

相关问题