在 october cms 的验证消息中显示图像索引

show index of the image in the validation message in october cms

我正在构建一个使用 OctoberCMS 上传多张图片的功能。验证工作正常。我要的是,当我们上传多张图片时,如果有一张图片不符合验证规则,就会出现这样的错误信息。

能不能把progress_image.3改成3rd image。如果是这样,则错误消息必须像这样显示。

The 3rd image has invalid image dimensions.

我想在消息中显示图片的索引。有什么建议么?想法?

这些是我的验证规则。

protected $rules = [
    'progress_date' => 'required',
    'progress_image' => 'required',
    'progress_image.*' => 'image|mimes:jpeg,jpg,png|dimensions:width=800,height=500|max:2048'
];

这是我的亲戚。

public $attachMany = [
    'progress_image' => 'System\Models\File'
];

您可以将第三个参数传递给 $request->validate(),它允许您覆盖要显示的验证消息,从而允许您传递自定义错误消息:

$messages = [];

foreach ($this->progress_image as $key => $val) {
    $messages['progress_image.' . $key . '.dimensions'] = 'The ' . ($key + 1) . ' image has invalid dimensions.';
}

然后当你调用$request->validate()时一定要用$messages传递第三个参数。

也许你可以试试 Validator::replacer

Plugin.php

// ...
use Validator;
use RainLab\Pages\Controllers\Index as PageController;

class Plugin extends PluginBase
{
    public function boot() {

      Validator::replacer('required', function($message, $attribute, $rule, $parameters) {

          // if attribute match with proper signature
          if(starts_with($attribute, 'progress_image.')) {
            $attributeArr = explode('.', $attribute);
            $newMessage = strtr($message, [$attribute => " image no. $attributeArr[1] "]);
            return $newMessage;
          }

          // otherwise return message as it is
          return $message;
      });

      // ...

** 我只是用普通消息对其进行了测试并且效果很好,但是对于您的场景,我尝试了一些解析和替换字符串但无法在那种字段上进行测试,因此您可能需要稍微调整一下。

参考:https://octobercms.com/docs/services/validation#custom-error-messages

Note : It will run for all fields with required validator.

如有疑问请评论。