我正在使用 parsley.js 进行客户端验证,并且还希望将其用于服务器端验证(Laravel Form Validator)< / strong>使用欧芹样式显示错误。所以它是统一的。
因此,每当我的服务器端验证失败时,我想显示与正确字段关联的特定错误。我不想使用远程库。
有一个例子怎么做?
非常感谢!
答案 0 :(得分:1)
您可以这样做:
<div>
{{ Form::open(['route' => 'dashboard.testform', 'id' => 'testForm']) }}
<div class="form-group row">
{{ Form::label('field1',
'Field 1',
['class' => 'col-xs-2']
) }}
<div class="col-xs-10">
<?= Form::text('field1', null, ['class' => 'col-xs-12 required ' . ($errors->has('field1') ? 'parsley-error' : '') ]) ?>
@if ($errors->has('field1'))
<ul class="parsley-errors-list filled">
{{ $errors->first('field1', '<li class="parsley-required">:message</li>') }}
</ul>
@endif
</div>
</div>
<div class="form-group row">
{{ Form::label('field2', 'Field 2', ['class' => 'col-xs-2']) }}
<div class="col-xs-10">
<?= Form::text('field2', null, ['class' => 'col-xs-12 ' . ($errors->has('field2') ? 'parsley-error' : '') ]) ?>
@if ($errors->has('field2'))
<ul class="parsley-errors-list filled">
{{ $errors->first('field2', '<li class="parsley-required">:message</li>') }}
</ul>
@endif
</div>
</div>
<div class="form-group row">
{{ Form::label('field3', 'Field 3', ['class' => 'col-xs-2']) }}
<div class="col-xs-10">
<?= Form::text('field3', null, ['class' => 'col-xs-12 required ' . ($errors->has('field3') ? 'parsley-error' : '') ]) ?>
@if ($errors->has('field3'))
<ul class="parsley-errors-list filled">
{{ $errors->first('field3', '<li class="parsley-required">:message</li>') }}
</ul>
@endif
</div>
</div>
{{ Form::submit('Submit form', ['class' => 'btn btn-primary']) }}
{{ Form::close() }}
</div>
{{ HTML::style('http://parsleyjs.org/src/parsley.css') }}
{{ HTML::script('http://code.jquery.com/jquery-1.11.1.min.js') }}
{{ HTML::script('http://parsleyjs.org/dist/parsley.min.js') }}
<script type="text/javascript">
$(document).ready(function() {
$("#testForm").parsley();
});
</script>
你的控制器将如下所示:
public function testform() {
$rules = array(
'field1' => 'date',
'field2' => 'required'
);
$validator = Validator::make(
Input::all(),
$rules
);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
return Redirect::back();
}
创建一个回显输入和错误的custom Form Macro(如果存在)可能是个好主意。这样就简化了你的观点。