I have a regular Integer (Not nullable) in my model:
[Required]
[Range(0, Int32.MaxValue - 1)]
public int PersonId
{
get;
set;
}
In my WebApi
action, I accept an object that has that propery.
public IHttpActionResult Create([FromBody] Person person)
{
if (!ModelState.IsValid)
{
return BadRequest("Some error message.");
}
//Do some stuff with person...
}
Now, altough there is a Required
attribute on PersonId
, when a person is posted to this action, the ModelState.IsValid
property is true
.
I guess this is because Person
is created with default value, which is 0, I want to throw an error if there is no PersonId
field in the incoming JSON / query string request.
I can set PersonId to be Nullable, but that doesn't make sense.
Is there any easy way to validate the field exists and the integer is larger than 0 ? (without custom validators for that simple requirement)
Setting the [Required]
attribute doesn't do anything on an int, as far as I know. All [Required]
does is make sure the value is not null.
You can set [Range(1, Int32.MaxValue)]
to make sure that a correct value is added.
If you don't already do this, it might be a good idea to make a different model for your view and make the data annotations on this model. I use view models to make sure I don't pollute my "real" models with stuff that is not relevant to the whole domain. This way your PersonId can be nullable in your view model only, where it makes sense.
BindRequiredAttribute
can be used to
Quoting from this nice blog post about [Required]
and [BindRequired]
It works the same way as RequiredAttribute, except it mandates that the value comes from the request – so it not only rejects null values, but also default (or “unbound”) values.
So this would reject unbound integer values:
[BindRequired]
[Range(0, Int32.MaxValue - 1)]
public int PersonId
{
get;
set;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With