给定新规则对象时,Laravel自定义验证规则解析器中断

时间:2018-12-18 01:35:16

标签: php laravel laravel-5.6

我通过遵循Laravel文档https://laravel.com/docs/5.6/validation#custom-validation-rules为Laravel应用程序创建了一些新的验证规则,但是,当我尝试将规则注册到我的自定义请求规则数组中时,会引发错误:

#message: "trim() expects parameter 1 to be string, object given"
#code: 0
#file: "/Users/ari/Projects/dps/sites/acg/vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php"
#line: 217
#severity: E_WARNING

我的自定义规则-NotContainsEmail.php:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NotContainsEmail implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return (strpos($value, '@') !== false);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'This field cannot contain an email address.';
    }
}

我的请求-QuoteRespondRequest:

<?php namespace Client\Http\Requests\Quotes;

use App\Rules\NotContainsEmail;
use Client\Http\Requests\FormRequest;

class QuoteRespondRequest extends FormRequest
{
    public function rules()
    {
        return [
            'help' => ['string', 'nullable', new NotContainsEmail],
            'description' => ['string', 'nullable', new NotContainsEmail],
            'community' => ['string', 'nullable', new NotContainsEmail],
            'funding' => ['string', new NotContainsEmail],
        ];
    }
}

我对错误感到困惑,因为Laravel文档明确指出我可以通过一个对象,但是Illuminate\Validation\ValidationRuleParser.php@217显然无法处理对象。

我哪里出错了?

1 个答案:

答案 0 :(得分:1)

使用扩展 注册自定义验证规则的另一种方法是在Validator外观上使用extend方法。让我们在服务提供者中使用此方法来注册自定义验证规则: https://laravel.com/docs/5.7/validation

在AppServiceProvider中

public function boot()
{
    Validator::extend('NotContainsEmail', function ($attribute, $value, $parameters, $validator) {
        // code here
    });

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        //return str_replace(...);
    });
}