在十月厘米中的验证消息中显示图像的索引

时间:2018-11-16 11:48:56

标签: php arrays laravel validation octobercms

我正在构建一个使用OctoberCMS上传多张图片的功能。验证工作正常。我想要的是,当我们上传多张图像时,如果一幅图像不符合验证规则,则会显示错误消息。

october cms validation error message

是否可以将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'
];

2 个答案:

答案 0 :(得分:1)

您可以将第三个参数传递给$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

答案 1 :(得分:1)

也许您可以尝试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

  

注意:它将在具有必需验证器的所有字段中运行。

如有疑问,请发表评论。