动态更改 CakePHP 3 自定义验证规则消息

Dynamically change CakePHP 3 custom validation rule message

我有一个自定义验证方法,用于检查令牌值的字段以确保它们都存在于内容中。该方法工作正常,当内容中存在所有标记时它验证为 OK,当缺少一个或多个标记时抛出验证错误。

当我将自定义验证规则附加到 validationDefault() 中的 table 时,我可以轻松地应用验证错误消息来声明某些标记丢失。但是,我真正想做的是设置一条验证消息,以反映尚未设置哪些标记。如何在 CakePHP 3 中动态设置验证消息?在 CakePHP 2 中,我曾经使用 $this->invalidate() 来应用适当的消息,但这似乎不再是一个选项。

我的代码如下所示(我删除了实际的令牌检查,因为它与此处的问题无关):-

public function validationDefault(Validator $validator)
{
    $validator
        ->add('content', 'custom', [
            'rule' => [$this, 'validateRequiredTokens'],
            'message' => 'Some of the required tokens are not present'
        ]);

    return $validator;
}

public function validateRequiredTokens($check, array $context)
{
    $missingTokens = [];

    // ... Check which tokens are missing and keep a record of these in $missingTokens ...

    if (!empty($missingTokens)) {
        // Want to update the validation message here to reflect the missing tokens.
        $validationMessage = __('The following tokens are missing {0}', implode(',', $missingTokens));

        return false;
    }

    return true;
}

Read the API docs.

复制粘贴:

实体特征::错误()

Sets the error messages for a field or a list of fields. When called without the second argument it returns the validation errors for the specified fields. If called with no arguments it returns all the validation error messages stored in this entity and any other nested entity.

// Sets the error messages for a single field
$entity->errors('salary', ['must be numeric', 'must be a positive number']);

// Returns the error messages for a single field
$entity->errors('salary');

// Returns all error messages indexed by field name
$entity->errors();

// Sets the error messages for multiple fields at once
$entity->errors(['salary' => ['message'], 'name' => ['another message']);

http://api.cakephp.org/3.3/class-Cake.Datasource.EntityTrait.html#_errors

不确定自从 burzums 回答以来这是否有所改进。

但其实很简单。自定义验证规则可以 return true(如果验证成功)、false(如果不成功),但您也可以 return 字符串。该字符串被解释为 false,但用于错误消息。

所以你基本上可以这样做:

public function validationDefault(Validator $validator)
{
    $validator
    ->add('content', 'custom', [
        'rule' => [$this, 'validateRequiredTokens'],
        'message' => 'Some of the required tokens are not present'
    ]);

    return $validator;
}

public function validateRequiredTokens($check, array $context)
{
     $missingTokens = [];

     if (!empty($missingTokens)) {
         // Want to update the validation message here to reflect the missing tokens.
         $validationMessage = __('The following tokens are missing {0}', implode(',', $missingTokens));

         //Return error message instead of false
         return $validationMessage;
     }

     return true;
}

来自食谱:

Conditional/Dynamic Error Messages