我做了一个表单验证(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')
这应该是相当不言自明的
{{ 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
如果你真的想要优雅的话,你应该使用宏:
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
,这始终是定义的。
Alfred,你也可以这样做,认为这是相当简单的
{ Form::text('email', null, $attributes = $errors->has('email') ? array('class'=>'error') : array()) }}
<span class="errors">{{ $errors->first('email') }}
你的css类可以像这样
.errors { color: #F00; }
此错误仅在验证规则失败时执行