devbf
devbf

Reputation: 571

Add validation to InputSelect with default placeholder string

I´m using an InputSelect like this:

<InputSelect @bind-Value="ExampleName">
    <option>---</option>
    @foreach (var item in itemList)
    {
        <option>@item.Name</option>
    }
</InputSelect>
<ValidationMessage For="@(() => ExampleName)" />

The validation is implemented like this:

[Required(ErrorMessage = "Custom error message")]
public string ExampleName { get; set; }

If I select nothing from the input select, the validation works fine, because ExampleName does not contain anything and thus the [Required] attribute isn´t fulfilled. But as soon as I select a valid option, and select the placeholder (---) again, the validation tells me, that the input is valid. Of course it is, because --- is a string, but I don´t want it to be valid.

How can this option be included as non-valid?

Upvotes: 0

Views: 2689

Answers (2)

Daniel Carriveau
Daniel Carriveau

Reputation: 11

(Using .NET 6) An even better solution (imho) is to make the 1st element also hidden like the following:

<InputSelect @bind-Value="ExampleName">
    <option hidden value="">Select a Value</option>
    @foreach (var item in itemList)
    {
        <option>@item.Name</option>
    }
</InputSelect>

This hides the "placeholder" option and makes sure it cannot be a selected value.

Upvotes: 0

devbf
devbf

Reputation: 571

Took me some time, but a simple value="" added to the option like this:

<option value="">---</option>

solves the problem, as the value bound to the InputSelect now only contains an empty string and not the string "---".

Upvotes: 2

Related Questions