如何在 Laravel 5 中每个相关输入字段旁边显示验证错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36885413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Display Validation Errors Next to Each Related Input Field in Laravel 5?
提问by Matt Komarnicki
Default solution is trivial:
默认解决方案很简单:
@if (count($errors) > 0)
<ul id="login-validation-errors" class="validation-errors">
@foreach ($errors->all() as $error)
<li class="validation-error-item">{{ $error }}</li>
@endforeach
</ul>
@endif
and I can include errors.blade.php
anywhere.
我可以包括errors.blade.php
任何地方。
Is there any way to extract each element and display it next to input field that holds the value that failed?
有没有办法提取每个元素并将其显示在包含失败值的输入字段旁边?
I assume that would require me to define a lot of conditional if
statements next to each input, right?
我认为这需要我if
在每个输入旁边定义很多条件语句,对吗?
How to sort this problem? Could you give me any examples?
这个问题如何排序?你能给我举些例子吗?
Thanks.
谢谢。
回答by zorx
You can use something like this :
你可以使用这样的东西:
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
<label for="name" class="col-sm-3 control-label">Name: </label>
<div class="col-sm-6">
<input class="form-control" required="required" name="name" type="text" id="name">
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
回答by Deepesh Thapa
@Zorx has given a right solution. But what if there are multiple errors and you want to display all of them at once.
@Zorx 给出了正确的解决方案。但是如果有多个错误并且您想一次显示所有错误怎么办。
According to the documentation you could use:
根据您可以使用的文档:
Retrieving All Error Messages For A Field
检索字段的所有错误消息
foreach ($errors->get('email') as $message) {
//
}
If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:
如果您正在验证数组表单字段,您可以使用 * 字符检索每个数组元素的所有消息:
foreach ($errors->get('attachments.*') as $message) {
//
}
Retrieving All Error Messages For All Fields
检索所有字段的所有错误消息
foreach ($errors->all() as $message) {
//
}