Laravel/Blade:如何在表单中设置错误消息的样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24448404/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:42:46  来源:igfitidea点击:

Laravel/Blade: How to style error message in form

phplaravelblade

提问by Alfred Bez

I made a form with validation (laravel with blade template engine) and it works as expected.

我制作了一个带有验证的表单(带有刀片模板引擎的 laravel)并且它按预期工作。

Here's the code:

这是代码:

@if ($errors->first('email'))
  {{ Form::text('email', null, $attributes = array('class'=>'error')) }}
  {{ $errors->first('email', '<small class=error>:message</small>') }}
@else
  {{ Form::text('email') }}
@endif

Is there a cleaner solution?

有更清洁的解决方案吗?

I'd like to write Form::text('email')only once...

我只想写Form::text('email')一次...

回答by Kemal Fadillah

This should be fairly self-explanatory

这应该是不言自明的

{{ Form::text('email', null, $attributes = $errors->has('email') ? array('class'=>'error') : array()) }}
@if ($errors->has('email'))
    {{ $errors->first('email', '<small class=error>:message</small>') }}
@endif

回答by Tom Macdonald

You should use a macro if you really want to be elegant:

如果你真的想优雅,你应该使用宏:

Form::macro('textWithErrors', function($name, $value, $attributes, $errors){
    if ($errors->has($name)) {
        if (array_key_exists('class', $attributes)) {
            $attributes['class'] .= ' error';
        } else {
            $attributes['class'] = 'error';
        }
    }
    $output = Form::text($name, $value, $attributes);
    if ($errors->has($name)) {
        $output .= $errors->first($name, '<small class=error>:message</small>');
    }
    return $output;
});

Use Form::textWithErrors()in place of the Form::text()call, and pass in the errors MessageBag, which is always defined.

使用Form::textWithErrors()替代的Form::text()呼叫,并传递错误MessageBag,它总是被定义。

回答by blakroku

Alfred, you can also do this, think this is fairly simple

阿尔弗雷德,你也可以这样做,觉得这很简单

{ Form::text('email', null, $attributes = $errors->has('email') ? array('class'=>'error') : array()) }}
<span class="errors">{{ $errors->first('email') }}

Your css class can be something like this

你的 css 类可以是这样的

.errors { color: #F00; }

This errors is only executed when the validation rules fail

此错误仅在验证规则失败时执行