0

My form has a textbox, and 3 radio buttons. The radio buttons indicate what type of tool a user wants to use, but he needs to have them in his inventory. There are 3 types of tools, and each radio button can only be selected if he owns at least one of them.. I want to validate it to se if he actually owns one. In the sample below, the variables $tool1 - 3contain the count of how many of each tool the user has. (for example: $tool1 = 1, $tool2 = 3, $tool3 = 0) In this case, the validation should be Ok, if the user selected one of the first two radio buttons since he owns the tools needed, but should fail if he selects the third radio button.

The field 'tool' contains the actual selected tool, so tool can be tool1, tool2 or tool3.

$tool1;
$tool2;
$tool3;

$data = request()->validate([
        'name'=> 'required',
        'tool' => 'required',
    ]);

how can this be done?

1 Answer 1

1

The following data structure you can do some nice tricks with and should be obtainable as i understand your domain.

$tools = collect(['tool1' => $tool1, 'tool2' => $tool2, 'tool3' => $tool3]);

Find all tools where count is higher than 0, filter() removes all null values and since 0 == null. To validate the input, we only need the name, we get that with keys().

// Should return 'tool1' and 'tool2' in an array from your example
$toolsOwned = $toolsOwned->filter()->keys();

Now we can use the In() validation to check if input is correct.

use Illuminate\Validation\Rules\In;

...

'tool' => ['required', new In($toolsOwned->all())],
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! is there also a way to specify the error code displayed?
when a field fails validation, usually there is a error displayed, some text.. (sorry not a code, my fault) I'd like to tell that they do not own this tool...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.