如何在FormRequest中使用自定义验证?

时间:2019-05-01 18:18:04

标签: laravel laravel-5

我上课:

class CreateInvoiceRequest extends FormRequest
{
    public function messages()
    {
        return [
            'name' => 'required|string',
            'code' => 'required|string|unique: enterprise_invoces,code',
        ];
    }

    public function rules()
    {
        return [
            'name' => 'required|string',
            'code' => 'required|string|unique: enterprise_invoces,code',
        ];
    }
}

还有一个自定义验证类:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class InvoiceCode implements Rule
{
    public function passes($attribute, $value)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The invoice code sholud be in formar <number>.<number>';
    }
}

如何在内部验证器应用InvoiceCode规则:

public function rules()
{
    return [
        'name' => 'required|string',
        'code' => 'required|string|unique: enterprise_invoces,code',
    ];
}

我尝试过:

 return [
                    'name' => 'required|string',
                    'code' => 'required|string|unique: enterprise_invoces,code',
                    'code' => new InvoiceCode()
                ];

2 个答案:

答案 0 :(得分:1)

在上一个代码段的规则数组中,您有重复的键。

要使用内置规则定义自定义规则,您可以传入数组而不是像这样的字符串:

return [
    'name' => 'required|string',
    'code' => ['required', 'string', 'unique: enterprise_invoces,code', new InvoiceCode()],
];

在此处记录:https://laravel.com/docs/5.8/validation#custom-validation-rules

答案 1 :(得分:1)

首先,您在FormRequest类上的messages方法不正确。如果要覆盖默认消息,则语法应为:

public function messages()
{
    return [
        'name.required' => 'The name is required.',
        'name.string' => 'The name should be a string',

        // keep adding the messages for the rules you want to override
    ];
}

对于rules方法,当属性具有多个规则以使其更易于阅读并且需要包含更复杂的逻辑时,通常使用数组。看起来应该像这样


public function rules()
{
    return [
        'name' => 'required|string',
        'code' => [
            'required',
            'string',
            'unique:enterprise_invoices,code', //you misspelled enterprise_invoices in your code
            new InvoiceCode
        ],
    ];
}