Plain Dev Blog
← Back to all posts

Validate MultiSelect field — Laravel Nova

·

Validate MultiSelect field — Laravel Nova

I’ve needed to make a simple validation for a MultiSelect field in Laravel Nova, so normally I’ve did something along the lines of

Multiselect::make('List')->rules('required')

And and I thought that will be it…it wasn’t it did not do anything basically the form can still be saved with the MultiSelect without anything selected.

That made me think 🤔

What I’m missing?

After a brief search, I found out that there are a few other rules that should be added which ultimately didn’t made difference in the end.

One of which was JSON which I’ve tried also, without any success really.

After a bit of search I’ve stumbled upon an issue in GitHub which was exactly about what I was looking for it turns out it was converted into a discussion in which I found the answer I was looking for:

->rules('required', 'json', function($attribute, $value, $fail) {
        $options = ['Option A', 'Option B', 'Option C'];
        $valueArray = json_decode($value);
        $containsOption = array_intersect($options, $valueArray);
        if(empty($containsOption)) {
          $fail('The selected reason should contain at least one allowed option.');
        }
})

Passing callback to the rules in which all custom validation can be made for me the check was:

function ($attribute, $value, $fail){
 if(empty(json_decode($value)){
   $fail('Please select an option')
  }
}

the full validation I’ve ended up with:

Multiselect::make('List')->required()
->rules('required', 'json', function ($attribute, $value, $fail) {
       if (empty(json_decode($value))) {
            $fail('Please select an option.');
       }
});

It’s working because when no option is selected the value is “[]” that’s why it needs to be JSON decoded before checking if it’s empty. It’s using JSON because in order to use that type of field the column in the DB should be JSON.

It’s simple solution that works, the weird thing is that there is nothing in the documentation regarding validation of MultiSelect field.

In any case, I found the solution I needed.

Conclusion

Laravel Nova has a lot of features that can be easily missed, lots of times I found myself reaching for the documentation or asking a question the support(for me the always had the answers of my questions). If the answer you looking for is not in the docs or the support can't help you, there are a lot of custom packages created for variety of functionalities