0

In my laravel (5.7) app I have a form request with an array of input fields. The Array "answers" has 8 distinct input fields. Until now I've been able to have a validation rule that checks each of the elements are at least 10 characters long.

class MyFormRequest extends FormRequest
{
    public function rules()
    {
        $rules = [
                    'answers'                  =>'required',
                    'answers.*'                =>'required|min:10', 
        ];
    }
}

but I want to change the requirement to only apply to 4 of the input fields, regardless of order. So if for example the user filled input fields number 1,5,6,8, each with 10 characters, the form would be accepted although fields 2,3,4,7 are empty. How can I achieve this? I read in the documentation that one can use the sometimes rule, but the examples use it in the controller and I don't undertand how I apply a custom sometimes rule in the FormRequest class.

Thanks in advance!

Wolfie
  • 31
  • 11

1 Answers1

0

Try this;

$rules = [
    'answers' => 'required|array|min:4',
    'answers.*' => 'sometimes|min:10', 
];

meaning;

"answers" -> answers is an array, has at least 4 indexes,

"answers.*" -> in answers array, indexes should validate when it present

Check Validating When Present and Validating Arrays

M. Tahir
  • 364
  • 1
  • 8
  • Thanks, I tried it, but it doesn't work correctly, as all 8 input fields are always there. some of them just need to be empty. So the min:4 is always valid, no matter how many fields were actually filled and then each input field is checked for 10 characters. – Wolfie Mar 24 '20 at 18:01
  • It is probably because of this https://laravel.com/docs/7.x/validation#a-note-on-optional-fields . you can set null variables to empty string or remove them before validation. For modify data before validation, check this one https://stackoverflow.com/questions/35246487/laravel-5-1-modify-input-before-form-request-validation – M. Tahir Mar 24 '20 at 18:33
  • Hmmm I'm not sure I got it. I actually want empty strings to be invalid, but they are getting validated anyway – Wolfie Mar 24 '20 at 20:20