0

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

It looks even great if you put the <option value="">---</option> on top of a 'optgroup` tag like this. <InputSelect class="form-control" @bind-Value="_associationToCreate.SportingCode"> <option value="">---</option> <optgroup label="Select sporting code"> @foreach (var enumeration in Enumeration.GetAll<SportingCode>()) { <option value="@enumeration">@enumeration</option> } </optgroup> </InputSelect>
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.