I like to think of DataAnnotation's validation in models as being "messages" intended for the end user, which indicates what needs to be done to make the entered data considered to be correct.
When a model has a property whose type is struct
nullable (such as Int32?
, DateTime?
, Double?
, and so on), and at the same time has the Required
annotation in one of these properties, it is as if the program said so to the user:
Dear user, this template is only valid when the P property is filled.
You can even stop filling the value of it (after all it is nullable), but in this case I (the program)
I will not save anything and I will show you an error message.
For me, all% validation% s are used to restrict the possibilities of the data type used, ie making possible values invalid for the data type.
In my view, the DataAnnotation
attribute should only be applied to properties whose data type can be overridden . That is, the attribute serves to invalidate the possibility that the data type gives.
Responding to your questions more directly:
-
Q: And if I put the required annotation on the property, is it required not having the value to be null or would it?
-
R: when the property is required the value can be null anyway ... occurs when the user leaves the field blank, in which case the
Required
will indicate an error in the model
-
Q: Why would anyone use this? if there is the possibility that the value is null why not just leave without ModelState
%
-
R: If the property type is
?
(or any other struct) and no int
, this automatically implies a required field ... as if Required
was there. In this example, if the user leaves the field blank, the value associated with the template will be Required
default: int
which is default(int)
, 0
will indicate that the property contains an error because it was not filled .