This is the custom rule class
<?php
namespace app\common\rules;
use app\admin\model\SystemPost;
use Respect\Validation\Rules\AbstractRule;
class LxUniqueRule extends AbstractRule
{
public function validate($input): bool
{
if (SystemPost::where('name', $input)->exists()){
return false;
}
return true;
}
}
This is how I use it
<?php
namespace app\admin\validator;
use app\admin\model\SystemPost;
use app\common\rules\LxUniqueRule;
use Respect\Validation\Validator;
class SystemPostValidator
{
public static function rules()
{
return [
'name' => Validator::create()->addRule(new LxUniqueRule())->notEmpty()
->setName('name'),
'code' => Validator::notEmpty()->alnum()->callback(function ($value) {
if (request()->method() == 'POST') {
return !SystemPost::where('code', $value)->exists();
}
if (request()->method() == 'PUT') {
$id = request()->post('id');
return !SystemPost::where('code', $value)->whereKeyNot($id)->exists();
}
})->setName('code'),
];
}
}
Now, I would like to know how to prompt a custom error message when LxUniqueRule rule validation fails. For example, name already exists, which is a public rule class. Can you help write an implementation method? Thank you very much
This is the custom rule class
This is how I use it
Now, I would like to know how to prompt a custom error message when LxUniqueRule rule validation fails. For example, name already exists, which is a public rule class. Can you help write an implementation method? Thank you very much