首页 > 解决方案 > Lang 文件上的 Laravel 验证

问题描述

我正在使用 laravel 5.8,并且在我的 resource/lang/xx/ 文件夹中包含了一个validation.php。

在我的控制器中,我使用此代码来验证字段:

$validator = Validator::make($request->all(), [
            'lastname' => 'required',
            'firstname' => 'required',
            'gender' => 'required',
            'birthplace_id' => 'required',
            'birthdate' => 'required',
            'fiscal_code' => 'required|unique:customers,fiscal_code,NULL,id,deleted_at,NULL',
        ]);

我不需要返回 $validator,但我需要在同一个函数中打印错误。我写了这段代码:

if ($validator->fails()) {
                \Log::info(json_encode($validator));
}

我得到了这个:

{
        "customMessages": [],
        "fallbackMessages": [],
        "customAttributes": [],
        "customValues": [],
        "extensions": [],
        "replacers": []
}

这是我的validation.php 文件的内容:

return [

/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/

'required' => 'The :attribute field is required.',
'unique' => 'Il :attribute è già stato utilizzato.',

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
],

/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/

'attributes' => [],

];

如何将我的验证器连接到 validation.php 语言文件?

标签: phplaravel

解决方案


它应该自动连接到 validation.php 文件

尝试以这种方式使用它:

$request->validate([
   'lastname' => 'required',
   'firstname' => 'required',
    'gender' => 'required',
    'birthplace_id' => 'required',
    'birthdate' => 'required',
    'fiscal_code' => 'required|unique:customers,fiscal_code,NULL,id,deleted_at,NULL'
]);

推荐阅读