Search code examples
c#asp.net-coreasp.net-core-webapimodel-validation

ASP.NET core model validation doesn't work as expected


According to Microsoft documentation, if a model property is not-nullable, it is considered required by default, so there's no need to explicitly add the [Required] attribute.

By default, the validation system treats non-nullable parameters or properties as if they had a [Required] attribute. Value types such as decimal and int are non-nullable. https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#required-attribute

But that's not practically true. Let's say I have the following model:

public class Model
{
    [Required]
    public string Name { get; set; }
    public int Age { get; set; }
}

If the request doesn't contain Age in its body, a 0 is bound to the Age property and model validation doesn't fail. Even with [Required], model validation still doesn't fail and 0 is assigned to Age. So how do I make properties with not-nullable types really "required"?


Solution

  • Three options imho:

    • Validate yourself that Age is not the default value
    • Use a Range attribute
    • Make it required and nullable
    [Required]
    public int? Age { get; set; }
    

    It depends very much on your circumstances if nullable-required is a nice solution or just a dirty workaround.