Search code examples
laravellaravel-8laravel-validation

Laravel minmum characters on condition ( depends on condition )


I have a scenario that the field should have min:5 only if another request field exists? Not required_if. Like if I have a products return reasons : if the user chooses a reason and wants to add some details to the textarea (input ) so I do not need any minimum characters, while if he chooses ( Other ) reason, I do need at least 5 chars?

Here is my validation rule :

'item.*.reason' => ['required_if:item.*.selected_reason,other','nullable','min:5','max:3000']

Solution

  • I did that with custom validation

    $validator = Validator::make($request->all(), [
        'reason' => ['required'], // may be enum
        'remarks' => [
            function ($attribute, $value, $fail) use($request) {
                if ($request->reason === "other" && strlen($value) < 5) {
                    $fail('Please provide a detailed reason.');
                }
            },
        ],
    ]);