Skip to content
Advertisement

Laravel Validation- depends on the value of another input field

I have 2 fields status and releaseYear and productionYear. I have to put the validation that :

 $request->
    'productionYear' => 'nullable|digits:4',
    'releaseYear'    => 'required|digits:4|after_or_equal:year_of_production',
    'status'         =>'required|in:Released,UnReleased',
 ]);

How do i put the following validations: If status is set to Released, then Year of Production and Year of Release should not be greater than this year.

If status is set to Un-Released, then Year of Production should not be greater than one year from this year

Advertisement

Answer

You can try custom validation like below. I have not tested, hope this will give you an idea.

    use IlluminateSupportFacadesInput;


    'status'         => 'required|in:Released,UnReleased',
    'productionYear' => [
            'nullable',
            'digits:4',
            function($attribute, $value, $fail) {
                $status = Input::get('status'); // Retrieve status

                if ($status === 'Released' && $value > now()->year) {
                    return $fail($attribute.' is invalid.');
                } elseif ($status === 'UnReleased' && $value > (now()->year + 1)) {
                    return $fail($attribute.' is invalid.');
                }
            },
        ],
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement