<?php
namespace app\validate\admin;
use think\Validate;
use think\facade\Db;
class UsersValidate extends Validate
{
protected $rule = [
'name' => 'require',
'id_card' => 'require|idCard',
'phone' => 'require|checkUnique:users,phone,id',
];
protected $message = [
'name.require'=> '姓名必须填写',
'id_card.require'=> '身份证号必须填写',
'id_card.idCard'=> '身份证号格式不正确',
'phone.require'=> '手机必须填写',
'phone.checkUnique'=> '手机号已存在',
];
protected function checkUnique($value, $rule, $data)
{
[$table, $field, $id] = explode(',', $rule);
$idField = $id ?: 'id';
$idValue = $data[$idField] ?? null;
$map = [
[$field, '=', $value],
];
if (!is_null($idValue)) {
$map[] = [$idField, '<>', $idValue];
}
return !Db::table($table)->where($map)->count();
}
}
控制器中调用
$data = $this->request->params(['name','phone','id_card','id']);
$validate = new UsersValidate();
$validate->check($data);