I like to think of Dataannotation`s validation in the models as being "messages" intended for the end user, which indicate what it is necessary to do in order for the entered data to be considered correct.
When a model has a property whose type is a struct
nullable (such as Int32?
, DateTime?
, Double?
, among others) and at the same time has the annotation Required
in one of these properties, it is as if the program says so to the user:
Mr user, this model is only valid when the P property is filled.
You can even fail to fill the value of it (after all it is nullable), but in this case I (the program)
I won’t save anything and I’ll show an error message.
For me, all the DataAnnotation
s of validation serve to restrict the possibilities of the type of data used, ie make invalid possible values for the type of data.
In my view, the attribute Required
should only be applied to properties whose data type can be overridden. That is, the attribute serves to make invalid the possibility that the data type gives.
Answering your questions more directly:
Q: And if I put the required Annotation in the property, being required it would have no value to be null or would have?
- R: when the property is required the value can still be null... occurs when the user leaves the field blank, in which case the
ModelState
will indicate an error in the template.
Q: Why would anyone use this? if there is the possibility of the value being null why not just leave without the ?
- R: If the property type is
int
(or any other struct) and without Required
, this automatically implies a mandatory field... it’s as if the Required
were there. In this example, if the user leaves the field blank, the value associated with the model will be the int
pattern: default(int)
that is 0
, whereas the ModelState
indicate that the property contains an error as it has not been filled in.