Add validation to InputSelect with default placeholder string

2k views Asked by At

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?

1

There are 1 answers

1
devbf On

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 "---".