Check multiselect dropdown value

Hello I want to run validation and check if the multiselect is empty? How do I access the Games value and check if its blank or empty?

My multi select looks like this, and the two if statements are both ways I have tried to access the value and do a check for if user made a selection

<SfMultiSelect @ref="_gamesMultiSelectRef"TValue="Games" TItem="Games" Placeholder="Favorite Sports" DataSource="@LocalData" @bind-Value="@_gamesValue">
    <MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>

@code {

private List<string> ValidationErrors { get; set; } = new();
private SfMultiSelect _gamesMultiSelectRef = new();
private Games _gamesValue = new();

    public class Games
    {
        public string ID { get; set; }
        public string Text { get; set; }
    }
    List<Games> LocalData = new List<Games> {
    new Games() { ID= "Game1", Text= "American Football" },
    new Games() { ID= "Game2", Text= "Badminton" },
    new Games() { ID= "Game3", Text= "Basketball" },
    new Games() { ID= "Game4", Text= "Cricket" },
    new Games() { ID= "Game5", Text= "Football" },
    new Games() { ID= "Game6", Text= "Golf" },
    new Games() { ID= "Game7", Text= "Hockey" },
    new Games() { ID= "Game8", Text= "Rugby"},
    new Games() { ID= "Game9", Text= "Snooker" },
    new Games() { ID= "Game10", Text= "Tennis"},
    };


    private bool CheckIfValid()
    {
        ValidationErrors.Clear();

        if (_gamesMultiSelectRef.Value.Text.IsEmpty())
        {
            ValidationErrors.Add("Please select a game");
        }


        if (_gamesValue.Text.IsEmpty())
        {
            ValidationErrors.Add("Please select a game");
        }


        return ValidationErrors.IsEmpty();
    }

6 Replies 1 reply marked as answer

DR Deepak Ramakrishnan Syncfusion Team August 11, 2022 01:30 PM UTC

Hi Pavel,


Yes we can detect when the selection is made from the user by using OnValueSelect event , Also you can get the selected values through its event arguments . Kindly refer the below documentation for more details about it.



https://blazor.syncfusion.com/documentation/multiselect-dropdown/events#onvalueselect


Thanks,

Deepak R.



PA Pavel August 11, 2022 03:11 PM UTC

I need to access those values outside the onvalueselect event because CheckIfValid()  function is ran to check if user has a valid value.

if user never touches the multiselect and tries to submit the form, then the on value select event never triggers and therefore  CheckIfValid()  function is not hit.



PA Pavel August 11, 2022 03:13 PM UTC

        if (_gamesMultiSelectRef.Value.Text.IsEmpty())
        {
            ValidationErrors.Add("Please select a game");
        }


        if (_gamesValue.Text.IsEmpty())
        {
            ValidationErrors.Add("Please select a game");
        }

This is the part of the code I need to run outside the onvalueselect


SP Sureshkumar P Syncfusion Team August 12, 2022 05:29 AM UTC

Hi Pavel,

We suggest you use the TValue as List<Games> instead of Games. And validate the value as mentioned the below code example. We have validated the sample by using the button click event.

Find the code example here:

<SfMultiSelect @ref="_gamesMultiSelectRef" TValue="List<Games>" TItem="Games" Placeholder="Favorite Sports" DataSource="@LocalData" @bind-Value="@_gamesValue">

    <MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>

</SfMultiSelect>

 

<button @onclick="@CheckIfValid1">CheckIfValid</button>

 

@code {

 

    private List<string> ValidationErrors { get; set; } = new();

    private SfMultiSelect<List<Games>, Games> _gamesMultiSelectRef;

    private List<Games> _gamesValue { get; set; } = new List<Games>() { };

 

    public class Games

    {

        public string ID { get; set; }

        public string Text { get; set; }

    }

    List<Games> LocalData = new List<Games> {

    new Games() { ID= "Game1", Text= "American Football" },

    new Games() { ID= "Game2", Text= "Badminton" },

    new Games() { ID= "Game3", Text= "Basketball" },

    new Games() { ID= "Game4", Text= "Cricket" },

    new Games() { ID= "Game5", Text= "Football" },

    new Games() { ID= "Game6", Text= "Golf" },

    new Games() { ID= "Game7", Text= "Hockey" },

    new Games() { ID= "Game8", Text= "Rugby"},

    new Games() { ID= "Game9", Text= "Snooker" },

    new Games() { ID= "Game10", Text= "Tennis"},

    };

 

    void CheckIfValid1(){

        bool checkError = CheckIfValid();

    }

 

    private bool CheckIfValid()

    {

        ValidationErrors.Clear();

 

        if (_gamesValue == null || (_gamesValue != null && _gamesValue.Count < 1))

        {

            ValidationErrors.Add("Please select a game");

        }

        //if (_gamesValue.Text.IsEmpty())

        //{

        //    ValidationErrors.Add("Please select a game");

        //}

        //return ValidationErrors.IsEmpty();

        return ValidationErrors.Count > 0 ?  true: false;

    }

}

Find the modified sample in the attachment:

Regards,

Sureshkumar P


Attachment: MultiselectServer_ad7226d.zip

Marked as answer

JC Jasmine Champagne January 29, 2025 01:01 PM UTC

@Sureshkumar P has the right approach—using TValue="List

" is the best way to handle multi-selection properly. The key issue in the original code is that _gamesValue was treated as a single Games object instead of a List, which is why validation wasn’t working correctly. For those running into similar issues, a simple check like:

if (_gamesValue == null || _gamesValue.Count == 0)

{

    ValidationErrors.Add("Please select at least one game.");

}


ensures validation works even if the user never interacts with the dropdown. One thing to watch out for: if you pre-populate _gamesValue with an empty list (new List()), make sure the binding updates properly when users select/deselect values. Debugging @bind-Value behavior can save time when troubleshooting. Has anyone tested how this behaves when integrating with form validation libraries like FluentValidation? Curious if any extra tweaks are needed.


PK Priyanka Karthikeyan Syncfusion Team February 4, 2025 01:00 PM UTC

Hi Jasmine Champagne,

 

Thank you for your update.

 

We have prepared a sample demonstrating the integration of FluentValidation with the SfMultiSelect component. The validation works as expected, displaying an error message when no values are selected and clearing the message upon selection.

 

For your reference, please find the code snippet and the attached sample.

 

MultiselectDropdownFeatures.razor

 

​@page "/multiselectdropdown-features"
@using Syncfusion.Blazor.DropDowns
@using FluentValidation
@using MultiselectServer.Data
@inject IValidator<GamesSelectionModel> Validator

<SfMultiSelect TValue="List<Games>" TItem="Games" Placeholder="Favorite Sports"
              DataSource="@LocalData" @bind-Value="@model.SelectedGames">
   <MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>

<button @onclick="@CheckIfValid">Check If Valid</button>

@if (ValidationErrors.Any())
{
   <ul>
       @foreach (var error in ValidationErrors)
       {
           <li style="color: red;">@error</li>
       }
   </ul>
}

@code {
   private GamesSelectionModel model = new();
   private List<string> ValidationErrors { get; set; } = new();

   List<Games> LocalData = new List<Games> {
       new Games() { ID= "Game1", Text= "American Football" },
       new Games() { ID= "Game2", Text= "Badminton" },
       new Games() { ID= "Game3", Text= "Basketball" },
       new Games() { ID= "Game4", Text= "Cricket" },
       new Games() { ID= "Game5", Text= "Football" }
   };

   public class Games
   {
       public string ID { get; set; }
       public string Text { get; set; }
   }

   private async Task CheckIfValid()
   {
       ValidationErrors.Clear();
       var result = await Validator.ValidateAsync(model);

       if (!result.IsValid)
       {
           ValidationErrors.AddRange(result.Errors.Select(e => e.ErrorMessage));
       }
   }
}
 

GameSelectionModel.cs

​namespace MultiselectServer.Data;

public class GamesSelectionModel
{
   public List<MultiselectServer.Pages.MultiSelectDropdownFeatures.Games> SelectedGames { get; set; } = new();
}
 

GamesSelectionValidator.cs

 

​namespace MultiselectServer.Data;

using FluentValidation;
public class GamesSelectionValidator : AbstractValidator<GamesSelectionModel>
{
   public GamesSelectionValidator()
   {
       RuleFor(model => model.SelectedGames)
           .NotNull().WithMessage("Please select at least one game.")
           .NotEmpty().WithMessage("Please select at least one game.");
   }
}

 

 

Regards,

Priyanka K


Attachment: FluentValidation_212a7ad.zip

Loader.
Up arrow icon