Search code examples
laravellaravel-validation

Laravel 10 nested validation - require if current textarea has any text


I have following HTML (textareas with same name which will use nested validation) - there can be between 1 and 20 of this fields:

<div class="flex-1">
    <label for="meta" class="mb-0 sm:w-1/4 sm:ltr:mr-2 rtl:ml-2">Addition Description</label>
    <textarea id="meta" name="meta[]" rows="5" class="form-textarea" data-markdown="true" placeholder=""></textarea>
</div>

<div class="flex-1">
    <label for="meta" class="mb-0 sm:w-1/4 sm:ltr:mr-2 rtl:ml-2">Addition Description</label>
    <textarea id="meta" name="meta[]" rows="5" class="form-textarea" data-markdown="true" placeholder=""></textarea>
</div>

<div class="flex-1">
    <label for="meta" class="mb-0 sm:w-1/4 sm:ltr:mr-2 rtl:ml-2">Addition Description</label>
    <textarea id="meta" name="meta[]" rows="5" class="form-textarea" data-markdown="true" placeholder=""></textarea>
</div>

How can I create validation that will check if the textarea have any text, and if this text is more than 30 characters. My rules so far:

/**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                Rule::unique('skills')->ignore($this->skill),
            ],
            'ability' => [
                'required',
                Rule::in(Abilities::names())
            ],
            'type' => [
                'required',
                Rule::in(Types::names())
            ],
            'description' => [
                'required',
                'min:30'
            ],
            'meta.*' => [
                Rule::requiredIf(fn () =>
                    dd($this)
                )
            ]
        ];
    }

Solution

  • You can update meta.* in your rules() method like below.

    'meta.*' => [
                function ($attribute, $value, $fail) {
                    $hasText = !empty($value);
                    $textLength = strlen($value);
                    if ($hasText && $textLength < 30) {
                        $fail($attribute.' must be at least 30 characters.');
                    }
                },
            ],