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

时间:2014-06-27 09:28:31

标签: php laravel blade

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

以下是代码:

@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

有更清洁的解决方案吗?

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

3 个答案:

答案 0 :(得分:8)

这应该是相当不言自明的

{{ 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

答案 1 :(得分:1)

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

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;
});

使用Form::textWithErrors()代替Form::text()来电,并传递始终定义的错误MessageBag

答案 2 :(得分:0)

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

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

你的css类可以是这样的

.errors { color: #F00; }

只有在验证规则失败时才会执行此错误