Laravel validator custom error returns a prompt message and displays it in the front end

Time:2019-11-20

Preface

By default, laravel validator returns prompt messages in English. In most cases, we need to customize error return prompt messages. This article will show you how to customize error messages and show them in the front end.

Custom error message

Don’t blame me for being too direct

$messages = [
   'phone. Unique' = > 'duplicate phone number',
   'required' = > 'please fill in the information completely',
  ];

$this->validate($request, [
   'phone' => 'required|unique:table_name',
   'name' => 'required',
  ], $messages);

Is it very simple? Just add an array of prompt information in the parameter of the validate () method. The key of the array is the field. The verification method or the direct verification method. Obviously, the latter is applied to all. The former is applied to a certain field.

Of course, you may not use this method. Other verifiers are the same. Here:


$validator = Validator::make($input, $rules, $messages);

Yes, this is also the third parameter. It’s the same way as above.

Error prompt front end display

Let’s talk about how the front end displays these error prompts. Let’s print them one by one

@if ($errors->any())
 @foreach ($errors->all() as $error)
 <div role="alert">
  < strong > errors encountered: < / strong >
   {{ $error }}
  <button type="button" data-dismiss="alert" aria-label="Close">
   <span aria-hidden="true">×</span>
  </button>
 </div>
 @endforeach
@endif

Forgive me for the poor front-end, so I used the bootstrap style. In order to highlight the main part, the clothes of this code are as follows:


@if ($errors->any())
 @foreach ($errors->all() as $error)
   {{ $error }}
 @endforeach
@endif

Well, it’s refreshing in a moment.

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

What are the new methods of visual + map technology?

Last week, Ren Xiaofeng, chief scientist of Alibaba Gaode map, made a technical exchange with you on the development of computer vision related technology and the application in the field of map travel at the online live broadcast activity of “cloud dialogue” between senior students of Alibaba. The interaction between live broadcast is hot. Especially […]