admin管理员组

文章数量:1122846

I use the Laravel validator to dynamically validate a field like so:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;


                $validator = Validator::make(
                    data: (array)$parent,
                    rules: [
                        'code' => [Rule::in($allowedCodes)],
                    ]
                );

                if ($validator->fails()) { ... }

However, I want to be able to also allow missing/null values.

How can I do this? Adding null in the list of $allowedCodes does not seem to work.

Also, I try to avoid using the string representation of the in rule (that requires concatenating all allowed codes into a string.

I use the Laravel validator to dynamically validate a field like so:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;


                $validator = Validator::make(
                    data: (array)$parent,
                    rules: [
                        'code' => [Rule::in($allowedCodes)],
                    ]
                );

                if ($validator->fails()) { ... }

However, I want to be able to also allow missing/null values.

How can I do this? Adding null in the list of $allowedCodes does not seem to work.

Also, I try to avoid using the string representation of the in rule (that requires concatenating all allowed codes into a string.

Share Improve this question edited Nov 22, 2024 at 14:04 Tim Lewis 29.2k14 gold badges80 silver badges106 bronze badges Recognized by PHP Collective asked Nov 22, 2024 at 13:53 user2173353user2173353 4,6404 gold badges53 silver badges86 bronze badges 5
  • 1 Does rules: ['nullable', Rule::in($allowedCodes)] work? – Tim Lewis Commented Nov 22, 2024 at 14:03
  • @TimLewis I have tried that, but it didn't work. I guess both rules in the array must be met. – user2173353 Commented Nov 22, 2024 at 14:09
  • 1 Typically no, since some for rules, it's impossible for all of them to be satisfied... This should work, since the nullable rule allows the field to be blank (null), and if it isn't null, then it should check against the Rule::in(...) logic. What validation errors do you get when it fails? – Tim Lewis Commented Nov 22, 2024 at 14:12
  • @TimLewis Indeed, the reason it appeared not to be working was that I had another bug somewhere. – user2173353 Commented Nov 22, 2024 at 14:27
  • Oh, yeah, that would do it

    本文标签: phpLaravel ValidationHow can I make Rulein() allow missingnull valuesStack Overflow