内容简介:Laravel Validator 默认返回的是英文的提示消息,而大多数情况我们需要自定义错误返回提示消息,本文将介绍一下如何自定义错误消息,并在前端展示。别怪我太直接,代码奉上
Laravel Validator 默认返回的是英文的提示消息,而大多数情况我们需要自定义错误返回提示消息,本文将介绍一下如何自定义错误消息,并在前端展示。
自定义错误消息
别怪我太直接,代码奉上
$messages = [
'phone.unique' => '重复的电话号码',
'required' => '请将信息填写完整',
];
$this->validate($request, [
'phone' => 'required|unique:table_name',
'name' => 'required',
], $messages);
是不是很简单呀,只需要在 validate() 方法参数里面加个提示信息数组就好了,数组的key就是 字段.验证方式 或者直接 验证方式 ,很显然,后者是应用于所有的,前者是应用于某一字段。
当然,你可能不是用的这种方式,其他验证器的也是一样的,看这里:
$validator = Validator::make($input, $rules, $messages);
是的,这样写也是传第三个参数,跟上面的方式是一样的。
错误提示前端展示
接下来讲一下前端如何展示这些错误提示呢,来让我们挨个打印一下
@if ($errors->any())
@foreach ($errors->all() as $error)
<div class="center alert alert-danger alert-dismissible fade show" role="alert">
<strong>遇到错误: </strong>
{{ $error }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endforeach
@endif
原谅我前端太差,所以用了bootstrap的样式,为了突出主要部分,扒了这段代码的衣服是这样的:
@if ($errors->any())
@foreach ($errors->all() as $error)
{{ $error }}
@endforeach
@endif
嗯,瞬间清爽了很多。
以上所述就是小编给大家介绍的《Laravel Validator 自定义错误返回提示消息以及前端展示》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 前端如何定义一个常量
- 小说精品屋 - plus v3.3.0发布,支持前端多模版自定义
- Android 自定义 View (04自定义属性)
- Vue自定义组件(简单实现一个自定义组件)
- Android 自定义View:深入理解自定义属性(七)
- Qt编写自定义控件20-自定义饼图 原 荐
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Twenty Lectures on Algorithmic Game Theory
Tim Roughgarden / Cambridge University Press / 2016-8-31 / USD 34.99
Computer science and economics have engaged in a lively interaction over the past fifteen years, resulting in the new field of algorithmic game theory. Many problems that are central to modern compute......一起来看看 《Twenty Lectures on Algorithmic Game Theory》 这本书的介绍吧!