List The Conditional Validation Rules In Laravel Framework

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

Laravel provides several different approaches to validate your application's incoming data. By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful conditional validation rules.today we are going to discuss conditional validation in laravel

List The Conditional Validation Rules In Laravel Framework

Skipping Validation When Fields Have Certain Values

You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the exclude_if validation rule. In this example, the appointment_date and doctor_name fields will not be validated if the has_appointment field has a value of false:
 

$v = Validator::make($data, [
    'has_appointment' => 'required|bool',
    'appointment_date' => 'exclude_if:has_appointment,false|required|date',
    'doctor_name' => 'exclude_if:has_appointment,false|required|string',
]);
 

Alternatively, you may use the exclude_unless rule to not validate a given field unless another field has a given value:

$v = Validator::make($data, [
    'has_appointment' => 'required|bool',
    'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
    'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
]);
 

Validating When Present

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
 

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);


In the example above, the email field will only be validated if it is present in the $data array.

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a Validator instance with your static rules that never change:

$v = Validator::make($data, [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);


Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.
 

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});
 

The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is the rules we want to add. If the Closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:
 

$v->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});


The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files.

Example(1)


1.Create route in web.php as below created

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');


2.Create PostController uisng below command

php artisan make:controller PostController


3.Open app\Http\controller\PostController.php file and implement below code in it.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    public function Create(){

        return view('create');
    }
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'has_appointment' => 'required|bool',
            'appointment_date' => 'exclude_if:has_appointment,false|required|date',
            'doctor_name' => 'exclude_if:has_appointment,false|required|string',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                ->withErrors($validator)
                ->withInput();
        }

        // Store the blog post...
        return 'done';
    }
}


4.Now create and implement below code in create.blade.php file

<!DOCTYPE html>
<html>
<head>
    <title>Conditional Validation Rules In Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Conditional Validation Rules In Laravel</h1>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <div class="form-group col-sm-2"></div>
    <div class="form-group col-sm-8">
        <div class="well">
            <form method="post" action="{{url('post')}}">
                @csrf
                <div class="form-group col-sm-12">
                    <label for="appointment">Appointment For</label>
                    <input id="appointment" type="text" class="form-control "> </div>
                <div class="form-group col-sm-12">
                    <label for="appointment_date">Appointment Date</label>
                    <input id="appointment" type="text" class="form-control "></div>
                <div class="form-group col-sm-12">
                    <label>Doctor Name</label>
                    <textarea  class="form-control " type="textarea" name="doctor_name" ></textarea></div>
                <div class="form-group text-center">
                    <input  class="btn btn-primary" type="submit" >
                </div>
            </form>
            <div class="form-group col-sm-2"></div>
        </div>
    </div>
    <br>
</div>
</body>
</html>


5.Pass below url to see output

http://localhost/laraveldemoproject/public/post/create

 

Related Post