wojtek1904
wojtek1904

Reputation: 41

Validation, required if 2 other fields have specified values

I have validation in Laravel 10 that contains validation for company_description. I want it to be required when two other fields have specified values. I got this code:

'company_description' => [
                'string',
                'nullable',
                function ($attribute, $value, $fail) {
                    if (request()->input('offer_type_id') == 1 && request()->input('use_default_company_description') == false) {
                        if (empty($value) || $value == '') {
                            $fail('Company description is required.');
                        }
                    }
                },
            ],

but its not working. If nullable is removed its working, but I need this field to be nullable. What am I doing wrong?

Upvotes: 0

Views: 78

Answers (2)

Oluwasegun Ige
Oluwasegun Ige

Reputation: 54

nullable allows the field to be null, which oppose the custom validation rule you are trying to apply when offer_type_id == 1 and use_default_company_description == false. When nullable is present, it takes precedence

'company_description' => [
        'string',
        'nullable',
        function ($attribute, $value, $fail) {
            $offerType = request()->input('offer_type_id');
            $useDefault = request()->input('use_default_company_description');
    
            // If offer_type_id is 1 and use_default_company_description is false
            if ($offerType == 1 && $useDefault == false) {
                // Check if the company_description is null or empty
                if (!request()->filled('company_description')) {
                    $fail('Company description is required.');
                }
            }
        },
    ],

Kindly note the following

  1. request()->filled(): This helper checks if the input is present and not empty or null
  2. The fail() method will only be triggered if company_description is empty or not provided when offer_type_id == 1 and use_default_company_description == false

Upvotes: 0

Jon Menard
Jon Menard

Reputation: 384

Use the withValidator and a sometimes to conditionally add the required rule.

company_description' => ['string']

public function withValidator($validator) {
        $validator->sometimes('company_description', 'required', function ($input) {
            return $input->offer_type_id == 1 && $input->use_default_company_description == false;
        });
    }

Upvotes: 1

Related Questions