In a .NET Core 3.x application, I have a model like the following where a custom validation attribute [CustomValidator] is used. The error messages returned for CustomValidator doesn't have a $. prefix whereas the built-in JSON validator returns with the prefix. I'd like to have them consistent (either with $. prefix all the time or not). Any idea how could this be done?
Example model:
public class Dto
{
public float Price {get; set;}
[CustomValidator] public int? EntityID {get; set;}
}
where [CustomValidator] is a custom validation attribute which does something like this
public class CustomValidatorAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var isValid = CheckSomething(...);
return isValid
? ValidationResult.Success
: new ValidationResult($"Invalid value for Entity");
}
}
I validate model in the Controller.Action with
if (!ModelState.IsValid) return BadRequest(ModelState);
For the input:
{
"Price" : "abc"
}
it returns
{
...
"errors": {
"$.price": [
"The JSON value could not be converted to System.Single. Path: $.price | LineNumber: 7 | BytePositionInLine: 21."
]
}
}
whereas for the input:
{
"Price" : 1.0,
"EntityID": -1,
}
it returns
{
...
"errors": {
"EntityID": [
"Invalid value for Entity"
]
}
}
I'd like it to have the errors always having consistent property names e.g. Price and EntityID instead of $.price and EntityID