DanielFuerst's avatar

Form Request Validation and Conditional Rules

Hi there

I have set following validation rules in one of my downloads controller to check a file upload form:

        $messages = [
            'region_list.required' => 'You have to select at least one region if you do not add any location.',
            'location_list.required' => 'You have to select at least one location if you do not add any region'
        ];

        $v = Validator::make( $request->all(), [
            'download' => 'required|max:2000|mimes:pdf,docx,doc',
            'title' => 'required|min:6|max:150',
        ], $messages );
        $v->sometimes( 'location_list', 'required', function ($input) {
            return empty( $input->region_list );
        } );
        $v->sometimes( 'region_list', 'required', function ($input) {
            return empty( $input->location_list);
        } );

        if ($v->fails()) {
            return redirect()->back()->withErrors( $v->errors() );
        }

The form displays two multiple select input fields called region_list and location_list. Both select list are always present in the form, but the user has to select at least one region or one location to basically make the file available for either a region a location or both. If he however leaves both select lists blank, the validator should redirect back and throw an error.

The code as displayed here, works in my controller, however I would like to move it to a form request class. I tried to implement the idea from this thread (answer were a moreValidation function is implemented): http://stackoverflow.com/questions/28793716/how-add-custom-validation-rules-when-using-form-request-validation-in-laravel-5

However If I do so, I lose the download field in my request array. Do I really need to add an additional Service Provider or is it possible to achieve such a conditional rule in a form request class?

Thanks for your help,

Dani

Edit: I have just realised that the required_without validation rule does the trick for me. So no need for the additional sometimes rule. However it remains the question, how I would implement this conditional rule in a form request class if I would ever need it.

Edit2: In another example I have managed to add a custom validation rule by the help of a ServiceProvider. See following thread https://laracasts.com/discuss/channels/general-discussion/validation-startend-date-with-min-and-max-amount-of-days-inbetween

0 likes
0 replies

Please or to participate in this conversation.