0

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

PaulG
  • 13,871
  • 9
  • 56
  • 78
Iliyan Ivanov
  • 407
  • 1
  • 4
  • 17

1 Answers1

4

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.

Matthias
  • 1,267
  • 1
  • 15
  • 27
  • 2
    [`[BindRequired]`](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2#customize-model-binding-behavior-with-attributes) might be a better option for this. – Kirk Larkin May 14 '19 at 09:03
  • @KirkLarkin still ModelState.IsValid is true, maybe it just work before entring action with ```opt.SuppressModelStateInvalidFilter = value;``` set to `default`, or `false`, but not `true`. – Hassan Faghihi Nov 17 '20 at 06:16