Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for a property to be [Required] and nullable?

People also ask

What is a nullable property?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

Can a required field be nullable?

Model fields can have required and nullable properties in the same way as a request parameter itself. Regardless of the type of data being passed, optional and nullable is in context to the representation of that data in JSON string during serialization.

How do you make a property nullable?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

How do you check if a property is nullable?

To check if PropertyType is nullable, we can use `System. Nullable. GetUnderlyingType(Type nullableType)`, see example below and reference here.


The reason for making a property nullable and marked with the [Required] attribute is to protect against under-posting attacks. It also allows you to display an initial empty value in the view rather than the default value for the property. This is typically done with value type properties in view models.

An under-posting attack is where a malicious user modifies the request to omit a value for the property in the request. If the property was DateTime (not nullable), then the DefaultModelBinder will initialize the value its default (01/01/0001) and no ModelState error would be generated. As a result, that value may then be saved even though its not what you may be expecting.

If the property is DateTime? (nullable) and [Required], then if a malicious user did omit the property in the request, then a ModelState error will be generated because a value is expected in the request, and the view would be returned, therefore the invalid data will not be saved.

Refer also Brad Wilson's article Input Validation vs. Model Validation in ASP.NET MVC and the section titled The "Under-Posting" Problem.


It's nullable so the form doesn't display an initial value like 0001-01-01T00:00:00 that has no meaning.

It's required to force the user to enter something.


Required is a data annotation for the view. The view will require it to have a value prior to accepting a form post.

That the value is nullable is related to what is allowed in the database. A value may be null in the database, or the value may be persisted as null.

They are separate aspects.


It is required for client validation but nullable for DB mapping