Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation- depends on the value of another input field

Tags:

php

laravel

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

like image 353
Sonal Avatar asked Sep 24 '18 02:09

Sonal


2 Answers

You can use rule lte like this:

'productionYear' => 'nullable|digits:4|lte:releaseYear',
'releaseYear'    => 'required|digits:4',

Please refer to docs.

like image 91
Carter Avatar answered Oct 21 '22 13:10

Carter


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

    use Illuminate\Support\Facades\Input;


    '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.');
                }
            },
        ],
like image 43
Saumini Navaratnam Avatar answered Oct 21 '22 13:10

Saumini Navaratnam