2

我正在使用尊重/验证,并创建了以下规则来验证和关联数组:

Validator::keySet(
        Validator::key( // mandatory, if included type: string, values: not null, not empty
            'name',
            Validator::stringType()->notEmpty()
        ),
        Validator::key( // mandatory, if included type: string, values: not null, not empty
            'company',
            Validator::stringType()->notEmpty()
        ),
        Validator::key( // mandatory, if included type: string, values: not null, not empty
            'type',
            Validator::stringType()->notEmpty()
        ),
        Validator::key( // mandatory, if included type: string, values: not null, not empty
            'country',
            Validator::stringType()->notEmpty()
        ),
        Validator::key( // optional, if included type: string, values: not null, not empty
            'comment',
            Validator::stringType()->notEmpty(),
            false
        )
    );

当我验证一个数组时,它可以正常工作,但是如果缺少一些强制键(比如说“公司”键),我总是会收到如下错误消息:

- Must have keys { "name", "company", "type", "country", "comment" }

但我想自定义错误消息并得到类似的东西:

"company" field is missing

我试过了:

$errors = $exception->findMessages([
...
'keyset' => '{{name}} field is missing',
....
]);

{{name}}包括带有键和值的整个数组...

有什么方法可以获取自定义错误消息?我应该包括另一个{{placeholder}}吗?

提前致谢

4

1 回答 1

0

您可以尝试以下一些方法:

Validator::key( // mandatory, if included type: string, values: not null, not empty
        'company',
        Validator::stringType()->notEmpty()->setName('company')
    ),

或者

Validator::key( // mandatory, if included type: string, values: not null, not empty
        'company',
        Validator::stringType()->notEmpty()->setName('company')->setTemplate('"{{name}}" field is missing')
    ),

https://respect-validation.readthedocs.io/en/1.1/feature-guide/#validator-name

验证者名称

在 v::attribute() 和 v::key() 上,{{name}} 是属性/键名。对于其他人,与输入相同。您可以使用以下方式自定义验证器名称:

v::date('Y-m-d')->between('1980-02-02', 'now')->setName('Member Since');

https://respect-validation.readthedocs.io/en/1.1/feature-guide/#exception-types

异常类型

Respect\Validation\Exceptions\ExceptionInterface:
    All exceptions implement this interface;
Respect\Validation\Exceptions\ValidationException:
    Implements the Respect\Validation\Exceptions\ExceptionInterface interface
    Thrown when the check() fails
    All validation exceptions extend this class
    Available methods:
        getMainMessage();
        setMode($mode);
        setName($name);
        setParam($name, $value);
        setTemplate($template);
        more...
Respect\Validation\Exceptions\NestedValidationException:
    Extends the Respect\Validation\Exceptions\ValidationException class
    Usually thrown when the assert() fails
    Available methods:
        findMessages();
        getFullMessage();
        getMessages();
        more...
于 2020-02-04T21:21:28.880 回答