Skip to content

Controller Validation Example

Omar Bahareth edited this page Jan 8, 2019 · 10 revisions

This is a basic example of how to reuse your validation rules in the controller .

PostController.php

<?php

namespace App\Http\Controllers;

use JsValidator;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Define your validation rules in a property in
     * the controller to reuse the rules.
     */
    protected $validationRules = [
        'title' => 'required|unique|max:255',
        'body' => 'required',
    ];

    /**
     * Show the edit form for blog post.
     * We create a JsValidator instance based on shared validation rules.
     *
     * @param  string|int  $post_id
     * @return \Illuminate\Http\Response
     */
    public function edit($post_id)
    {
        $validator = JsValidator::make($this->validationRules);
        $post = Post::find($post_id);
    
        return view('edit_post')->with([
            'validator' => $validator,
            'post' => $post,
        ]);
    }

    /**
     * Store the incoming blog post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validation = Validator::make($request->all(), $this->validationRules);
    
        if ($validation->fails()) {
            return redirect()->back()->withErrors($validation->errors());
        }
    
        // do store stuff
    }
}

In the view you simply should print the validator object passed to the view. Remember that this package depends of JQuery and you have to include before that jsvalidation.js

edit_post.blade.php

<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <form class="form-horizontal" role="form" method="POST" action="" id="my-form">
                <div class="form-group">
                    <label class="col-md-4 control-label">Title</label>
                    <div class="col-md-6">
                        <input type="text" class="form-control" name="title">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-4 control-label">Body</label>
                    <div class="col-md-6">
                        <textarea name="body"></textarea>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- Scripts -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>

<!-- Laravel Javascript Validation -->
<script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
{!! $validator->selector('#my-form') !!}
Clone this wiki locally