#Validation: required_unless

1 messages · Page 1 of 1 (latest)

tepid acorn
#

I'm struggling to get this validation to work the way I want

$validated = $request->validate([
    'title' => 'required|max:50',
    'locked' => 'boolean',
    'featured' => 'boolean',
    'flagship_id' => 'required_unless:featured,false|uuid'
]);

Payload

{
  "title": "Example title",
  "locked": true,
  "featured": false,
  "flagship_id": null
}

Error
The flagship id must be a valid UUID.

Description of rule requirements
flagship_id is required a valid UUID style value unless featured is equal to false then null should be accepted

ember sequoia
# tepid acorn I'm struggling to get this validation to work the way I want ```php $validated =...

You are going to have to use a custom validation rule:

$validated = $request->validate([
    'title' => 'required|max:50',
    'locked' => 'boolean',
    'featured' => 'boolean',
    'flagship_id' => [
        'required_unless:featured,false',
        function ($attribute, $value, $fail) {
            if ($value === null && request()->input('featured') === false) {
                return;
            }

            if (!is_string($value) || !preg_match('/^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/i', $value)) {
                $fail('The flagship id must be a valid UUID.');
            }
        },
    ],
]);

If you reuse this rule more than once you can make a custom validation rule class that extents rule & use (new CustomRule)

#

Might be neater to use a custom rule class even if you don’t reuse the logic, up to you!

use Illuminate\Validation\Rule;

class FlagshipIdRule extends Rule
{
    public function passes($attribute, $value)
    {
        if (request()->input('featured') === false && $value === null) {
            return true;
        }

        return is_string($value) && preg_match('/^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/i', $value);
    }

    public function message()
    {
        return 'The flagship id must be a valid UUID.';
    }
}

And then

$validated = $request->validate([
    'title' => 'required|max:50',
    'locked' => 'boolean',
    'featured' => 'boolean',
    'flagship_id' => [
        'required_unless:featured,false',
        new FlagshipIdRule(),
    ],
]);
tepid acorn
#

Thanks, I appreciate the guide (I've never needed to create a custom rule so this is helpful)
Can I ask why I'd need one. The manual states I can use required_unless:anotherfield,value,... where value is the value I'm looking for. They give an example of null as being that value but I'd be looking for false.
https://laravel.com/docs/9.x/validation#rule-required-unless

ember sequoia
#

I’m on my way home, so can’t try it out…

tepid acorn
#

Ah - yeah adding nullable worked, I never thought to add that since that's kind of what required_unless should mean.

#

Thanks very much CamKem

ember sequoia
#

All good then, and I was way overthinking it with custom rules 🤣