Skip to content Skip to sidebar Skip to footer

Parsley.js And Laravel Form Validation Errors

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. S

Solution 1:

You can do something like this:

<div>
    {{ Form::open(['route' => 'dashboard.testform', 'id' => 'testForm']) }}
    <divclass="form-group row">
        {{ Form::label('field1',
            'Field 1',
            ['class' => 'col-xs-2']
        ) }}
        <divclass="col-xs-10"><?= Form::text('field1', null, ['class' => 'col-xs-12 required ' . ($errors->has('field1') ? 'parsley-error' : '') ]) ?>
            @if ($errors->has('field1'))
                <ulclass="parsley-errors-list filled">
                    {{ $errors->first('field1', '<liclass="parsley-required">:message</li>') }}
                </ul>
            @endif
        </div></div><divclass="form-group row">
        {{ Form::label('field2', 'Field 2', ['class' => 'col-xs-2']) }}
        <divclass="col-xs-10"><?= Form::text('field2', null, ['class' => 'col-xs-12 ' . ($errors->has('field2') ? 'parsley-error' : '') ]) ?>
            @if ($errors->has('field2'))
                <ulclass="parsley-errors-list filled">
                    {{ $errors->first('field2', '<liclass="parsley-required">:message</li>') }}
                </ul>
            @endif
        </div></div><divclass="form-group row">
        {{ Form::label('field3', 'Field 3', ['class' => 'col-xs-2']) }}
        <divclass="col-xs-10"><?= Form::text('field3', null, ['class' => 'col-xs-12 required ' . ($errors->has('field3') ? 'parsley-error' : '') ]) ?>
            @if ($errors->has('field3'))
                <ulclass="parsley-errors-list filled">
                    {{ $errors->first('field3', '<liclass="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') }}

<scripttype="text/javascript">
    $(document).ready(function() {
        $("#testForm").parsley();
    });
</script>

And your controller will look like this:

publicfunctiontestform() {
    $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.

Post a Comment for "Parsley.js And Laravel Form Validation Errors"