问题
I am using parsley.js for a client-sided validation and also want to use it for the server-sided validation (Laravel Form Validator) to show the errors using the parsley styling. So that it is uniform.
So whenever my server-side validation fails, I would like to show the specific error associated to the correct field. I don´t want to use the remote library.
Is there an example how to do this?
Link to: Laravel Validator and Parsley
Thank you very much!
回答1:
You can do something like this:
<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>
And your controller will look like this:
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();
}
It might be a good idea to create a custom Form Macro that echos the input and the error, if it exists. That way your view is simplified.
来源:https://stackoverflow.com/questions/24540438/parsley-js-and-laravel-form-validation-errors