如何为多个输入字段设置单个自定义验证消息?

时间:2017-11-17 08:41:24

标签: php laravel laravel-5 laravel-5.3

public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    return [
      "skill" => "required|array",
      "skillyear.*" => "required_with:skill|numeric",
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyear.*.required_with'=>"Experience year is required for the selected skill"
];}

所以,对于每个领域,我都会收到这样的消息 enter image description here 我如何才能获得所有这些信息。

2 个答案:

答案 0 :(得分:0)

在控制器中使用简单的laravel验证:

    public function getRequest(Request $request) {

                    $this->validate($request, [
                        'param1' => 'required',
                        'param2' => 'required'
                    ], [
                      'required' => 'Field is required'  
                       ], [
                        'param1' => 'field name 1 - message',
                        'param2' => 'field name 2 - message'
                    ]);

更多:https://laravel.com/docs/5.5/validation

答案 1 :(得分:0)

更改如下。添加一个新元素skillyears,您将在skillyears中收到错误,以获得单个错误

public function rules(Request $request)
{
  if ($request->isMethod('POST')) {
    $request->skillyears = count($request->skillyear);
    return [
      "skill" => "required|array",
      "skillyear.*" => "numeric",
      "skillyears" => "required_with:skill|min:1"
    ];
  }
 public function messages()
{
 return [
     'skill.required'=>'Select at least one skill',
     'skillyears.min' => "Experience year is required for the selected skill",
];}

可能不准确,但您可以根据需要制作想法