验证器 - 返回所有错误消息

时间:2015-08-17 14:59:36

标签: php validation laravel laravel-5 laravel-5.1

目前,Laravel中的Validator似乎每个字段只返回一条错误消息,尽管该字段可能包含多个规则和消息。 (注意:我现在将一个空数组作为$ data传递给Validator :: make)

我要做的是构建每个字段的规则和消息的数组,这些规则和消息可能会被重新用于前端验证。像这样:

{
    "name": {
        "required": [
            "The name field is required."
        ],
        "max:255": [
            "The name field may not be greater than 255."
        ]
    },
    "email": {
        "required": [
            "The email field is required."
        ],
        "email": [
            "The email field must be a valid email address."
        ],
        "max:255": [
            "The email field may not be greater than 255."
        ]
    }
}

Illuminate \ Validation \ Validator中的getMessage方法看起来会让我接近能够自己构造一些东西,但它是一种受保护的方法。

有没有人知道如何让Validator实例输出所有规则和消息?

1 个答案:

答案 0 :(得分:2)

  

目前,Laravel中的Validator只会在每个字段中返回一条错误消息,尽管该字段可能包含多个规则和消息。

单个验证规则失败后,给定字段的验证将停止。这就是您每个字段只获得一条错误消息的原因。

在提取验证消息时,如您提供的示例中所示,Laravel的验证器不提供此类选项,但您可以通过扩展 Validator 类轻松实现此目的。

首先,创建新课程:

<?php namespace Your\Namespace;

use Illuminate\Validation\Validator as BaseValidator;

class Validator extends BaseValidator {
  public function getValidationMessages() {
    $messages = [];
    foreach ($this->rules as $attribute => $rules) {
      foreach ($rules as $rule) {
        $messages[$attribute][$rule] = $this->getMessage($attribute, $rule);
      }
    } 

    return $messages;
  }
}

正如您所看到的,输出与您的示例略有不同。没有必要为给定的属性和规则返回一组消息,因为数组中总会只有一条消息,所以我只是在那里存储一个字符串。

其次,您需要确保使用验证程序类。为了达到这个目的,您需要使用验证器外观注册您自己的验证器解析器:

Validator::resolver(function($translator, array $data, array $rules, array $messages, array $customAttributes) {
  return new \Your\Namespace\Validator($translator, $data, $rules, $messages, $customAttributes);
});

您可以在 AppServiceProvider :: boot()方法中执行此操作。

现在,为了获得给定验证器的验证消息,您只需要调用:

Validator::make($data, $rules)->getValidationMessages();

请注意,此代码尚未经过测试。如果您发现代码存在任何问题或拼写错误,请告诉我们,我们非常乐意为您提供帮助。