'ASP.Net Core Razor model validation for a <select> element

I have a .Net Core web application and I am trying to get the model validation to work as I want.

The razor code is

  <div class="form-group">
      <label asp-for="Duration"></label>
      <select asp-for="Duration" class="form-control">
          <option value="">Pick number of days</option>
          <option value="7">7 days</option>
          <option value="14">14 days</option>
          <option value="21">21 days</option>
          <option value="28">28 days</option>
      </select>
      <div><span asp-validation-for="Duration" class="text-danger"></span></div>
  </div>

The model is

  [Required(ErrorMessage = "The duration is required")]
  [Display(Name = "Length of audit:")]
  public int Duration { get; set; }

If I do not select any value, the drop down remains at "Pick number of days". The validation message that is shown is "The value '' is invalid."

Apart from creating my own custom validator, how can I get the code to generate the validation message of "The duration is required"



Solution 1:[1]

Change the data type for the Duration property to a nullable int:

public int? Duration { get; set; }

Solution 2:[2]

You could add required to the select list

  <select required asp-for="Duration" class="form-control">
      <option value="">Pick number of days</option>
      <option value="7">7 days</option>
      <option value="14">14 days</option>
      <option value="21">21 days</option>
      <option value="28">28 days</option>
  </select>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Brind
Solution 2 tdahman1325