ViewModel:
[Required]
public int Hours { get; set; }
Razor:
@Html.EditorFor(m => m.Hours)
Output:
<input type="text" value="0" name="Hours" id="Hours"
data-val-required="The field is required."
data-val-number="The field must be a number."
data-val="true" class="text-box single-line valid">
What gives, why is the value being automatically populated with 0. It is pretty much bypassing validation in that the user can submit this without actually entering anything.
Your property’s type is
intwhich is value type with the default value of0.If you want the Reuired attribute properly work make
Hoursnullable: