❔ Double property with [Required] data annotation does not validate
How can I make it so that the req body has to have a DiscountPercentage field?
10 Replies
you've just done it with that required
nope I was able to make requests without the field
found the solution, apparently I need to make the field nullable so - public double? DiscountPercentage { get; set; }
Stack Overflow
Required attribute for an integer value
I have a viewmodel with an Id property
[Required]
public int Id { get; set; }
But I think this attribute is working only for string properties.
When no Id is set, Id has value 0 and the model is...
huh
well, making it nullable is kinda ridiculous
what are you doing on frontend may I ask?
Sure, this is Web API
int, double, etc such datatypes assign default value to the variable that could be why it passes the validation
check out this
Stack Overflow
ASP.NET Core [Require] non-nullable types
Here, the question was posed how to validate non-nullable required types.
The provided solution to make the field nullable like the following is not desirable in my case.
[Required]
public int? D...
this one's only for newtonsoft tho, so probably not what you want
it seems like the best you can do with system.text.json is requiring a value for all properties, even if it's got a default value, but I'm not sure.
this should also work https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.bindrequiredattribute?view=aspnetcore-7.0
BindRequiredAttribute Class (Microsoft.AspNetCore.Mvc.ModelBinding)
Indicates that a property is required for model binding. When applied to a property, the model binding system requires a value for that property. When applied to a type, the model binding system requires values for all properties that type defines.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.