首页 > 解决方案 > 为同名但模型不同的表单字段添加验证规则

问题描述

在我的 Laravel 7 应用程序中,为了在表单中显示更好的错误消息,我使用了自定义验证属性。例如,对于在提交的表单字段中缺少时id显示的字段。inventory number needed现在的问题是我的应用程序中有几种不同模型的表单,并且有多个id字段。还有一个id是员工编号或流程编号。

但是在resources/lang/en/validation.php我看不到为不同模型定义相同字段名称的方法。我的想法是重命名该字段以进行错误检查,例如id重命名为employee_id但没有出现错误消息。

在我看来:

<div class="form-group{{ $errors->has('id') ? ' ' : '' }}">
  <input class="form-control{{ $errors->has('id') ? ' is-invalid' : '' }}" name="id" type="text" value="{{ old('id', $process->id) }}" aria-required="true"/>
  @include('alerts.feedback', ['field' => 'employee_id'])  //not working
</div>

从我的validation.php:

    'attributes' => [ 
        'email' => 'Mail Address',
        'old_password' => 'Current Password',
        'password' => 'Password',
        'id' => 'Inventory Number', //working, for other form/model
        'employee_id' => 'Employee ID' //not working
    ]

我认为问题在于只接受模型数据库中实际存在的字段名称。如何克服这一点?

标签: laravelformsvalidation

解决方案


我刚刚找到了解决方案:定义自定义错误属性的更好方法validation.php是为模型创建表单请求(https://laravel.com/docs/7.x/validation#creating-form-requests)并使用方法function attributes()。所以与其他模型字段名称没有冲突而且更清楚,因为属性是在模型的表单请求中设置的:

<?php
namespace App\Http\Requests;

use App\Employee;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class EmployeeRequest extends FormRequest
{
(...)
  public function attributes()
  {
    return [
      'id' => 'Employee ID',
    ];
  }
}

推荐阅读