Laravel 5.3 return custom error message using $this->validate()

前端 未结 4 995
星月不相逢
星月不相逢 2020-12-05 14:09

How to return a custom error message using this format?

$this->validate($request, [
  \'thing\' => \'required\'
]);
相关标签:
4条回答
  • 2020-12-05 14:35

    to get custom error message you need to pass custom error message on third parameter,like that

    $this->validate(
        $request, 
        ['thing' => 'required'],
        ['thing.required' => 'this is my custom error message for required']
    );
    
    0 讨论(0)
  • 2020-12-05 14:36

    You need to first add following lines in view page where you want to show the Error message:

    <div class="row">
            <div class="col-md-4 col-md-offset-4 error">
                <ul>
                    @foreach($errors->all() as $error)
                        <li>{{$error}}</li>
                    @endforeach
                </ul>
            </div>
        </div>
    

    Here is a demo controller by which error message will appear on that page:

    public function saveUser(Request $request)
    
     {
         $this->validate($request,[
            'name' => 'required',          
            'email' => 'required|unique:users',          
            ]);
      $user=new User();
      $user->name= $request->Input(['name']);
      $user->email=$request->Input(['email']);
      $user->save();
      return redirect('getUser');
     }
    

    For details You can follow the Blog post. Besides that you can follow laravel official doc as well Validation.

    0 讨论(0)
  • 2020-12-05 14:38

    https://laravel.com/docs/5.3/validation#working-with-error-messages

    $messages = [
        'required' => 'The :attribute field is required.',
    ];
    
    $validator = Validator::make($input, $rules, $messages);
    

    "In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file."

    0 讨论(0)
  • 2020-12-05 14:44

    For Multiple Field, Role and Field-Role Specific Message

    $this->validate(
            $request, 
            [   
                'uEmail'             => 'required|unique:members',
                'uPassword'          => 'required|min:8'
            ],
            [   
                'uEmail.required'    => 'Please Provide Your Email Address For Better Communication, Thank You.',
                'uEmail.unique'      => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
                'uPassword.required' => 'Password Is Required For Your Information Safety, Thank You.',
                'uPassword.min'      => 'Password Length Should Be More Than 8 Character Or Digit Or Mix, Thank You.',
            ]
        );
    
    0 讨论(0)
提交回复
热议问题