unlikenesses's avatar

Validate select dropdown with potential empty string

Assuming I have a form with this select tag:

<select name="foobar">
<option value="">Select:</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

I want this to be optionally empty (i.e. the first option), or to validate that the value selected exists in the database. But this validation option doesn't work:

'nullable|exists:foobar,id'

It will validate any selected option ok, but not the top (empty) option, I guess because an empty string is not null. I know there's a ConvertEmptyStringsToNull middleware but I'd rather not activate it if possible. What's the best practice here?

0 likes
6 replies
unlikenesses's avatar

Sorry Michal, I wrote a confused reply based on a misunderstanding on my side, so I've deleted it.

I do have that middleware activated. However even with this sometimes validation rule, I still get the "The selected foobar is invalid" error message.

I am using Livewire, if that makes a difference.

unlikenesses's avatar

Yes, 'nullable|exists:foobar,id' is what I wrote in my question.

Seems it's a Livewire issue.

Please or to participate in this conversation.