“方法[validateEach]不存在” Laravel 4.2

时间:2019-02-07 11:57:07

标签: php arrays laravel validation laravel-4.2

我已经创建了自定义验证器:

namespace App\Validators;

class PhoneValidationRule extends \Illuminate\Validation\Validator {

    public function validatePhone($attribute, $value, $parameters)
    {
        return preg_match("/^[\+]?[-()\s\d]{4,17}$/", $value);
    }
}

并注册:

class ValidatorServiceProvider extends ServiceProvider {


    public function boot()
    {
        \Validator::resolver(function($translator, $data, $rules, $messages)
        {
            return new PhoneValidationRule($translator, $data, $rules, $messages);
        });
    }
...

如果我在字段中调用它,它会很好:

        $validator = Validator::make($input, [
            'emails' => 'required|each:email',
            'phone' => 'required|phone',
        ]);

但是当我尝试将其应用于数组时

        $validator = Validator::make($input, [
            'emails' => 'required|each:email',
            'phones' => 'required|each:phone',
        ]);

我收到错误消息:

  

错误:{类型:“ BadMethodCallException”,消息:“方法   [validateEach]不存在。“,…}文件:   “ /home/.../vendor/laravel/framework/src/Illuminate/Validation/Validator.php”   行:2564消息:“方法[validateEach]不存在。”类型:   “ BadMethodCallException”

我在做什么错了?

3 个答案:

答案 0 :(得分:0)

您的问题是这部分:required|each

没有each验证规则。查看文档以获取可用验证规则的列表:docs

答案 1 :(得分:0)

验证单个字段

$validator = Validator::make($request->all(), [
    'email' => 'required|email',
    'phone' => 'required|phone',
]);

验证数组

$validator = Validator::make($request->all(), [
    'emails' => 'required|array',
    'emails.*' => 'email',
    'phones' => 'required|array',
    'phones.*' => 'phone',
]);

* Laravel 5.3 +

答案 2 :(得分:0)

each()

通过直接为自定义规则$v->each()调用本地方法phone解决了部分问题:

$validator = Validator::make($input, [
   'phones' => 'required|array',
]);

$validator->each('phones', ['required', 'phone']);

但是它允许您仅对值数组而不是对象进行迭代验证