Respect / Validation

The most awesome validation engine ever created for PHP
https://respect-validation.readthedocs.io
MIT License
5.75k stars 774 forks source link

How do custom validation rules throw custom error messages? #1437

Closed hcweb closed 4 months ago

hcweb commented 8 months ago

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

henriquemoody commented 4 months ago

I'm sorry I missed that. Is this still relevant? I'm happy to help.

henriquemoody commented 4 months ago

The answer should probably be here, anyways: https://respect-validation.readthedocs.io/en/2.3/06-custom-rules/

I will close this issue, but feel free to comment on it anytime! 🐼