尊重/验证:keySet 中的必需键,如何在错误消息中获取缺少的键名



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

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}}吗?

提前致谢

您可以尝试以下一些操作:

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

异常类型

RespectValidationExceptionsExceptionInterface:
    All exceptions implement this interface;
RespectValidationExceptionsValidationException:
    Implements the RespectValidationExceptionsExceptionInterface 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...
RespectValidationExceptionsNestedValidationException:
    Extends the RespectValidationExceptionsValidationException class
    Usually thrown when the assert() fails
    Available methods:
        findMessages();
        getFullMessage();
        getMessages();
        more...

最新更新