Skip to content

Conditional Validation Example

albertmoreno edited this page Jan 7, 2017 · 4 revisions

This is a basic example of how to use conditional validations.

PostController.php

namespace App\Http\Controllers;

use JsValidator;

class PostController extends Controller {

    /**
     * Define your validation rules in a property in 
     * the controller to reuse the rules.
     */
    protected $validationRules=[
            'email' => 'required|email',
            'games' => 'required|numeric',
    ];

    /**
     * Show the edit form for blog post
     * We create a JsValidator instance based on shared validation rules
     * @param  string  $post_id
     * @return Response
     */
    public function edit($post_id)
    {
        $jsValidator = JsValidator::make($this->validationRules);
        $jsValidator->sometimes('reason', 'required|max:500');

        $post = Post::find($post_id);
    
        return view('edit_post')->with([
            'validator' => $jsValidator,
            'post' => $post
        ])    
   
    }
    
    
    /**
     * Store the incoming blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $v = Validator::make($request->all(), $this->validationRules]);
        $v->sometimes('reason', 'required|max:500', function ($input) {
              return $input->games >= 100;
        });
        if ($v->fails())
        {
            return redirect()->back()->withErrors($v->errors());
        }
    
        // do store stuff
    }
}

To enable conditional validations, in the controller you need to specify the attribute adn rules to validate conditionally. This rules will be validated using Ajax

        $jsValidator->sometimes('reason', 'required|max:500');
Clone this wiki locally