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

0

1 Answer 1

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.

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

2 Comments

[BindRequired] might be a better option for this.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.