I have a C# WebApi project and i am using FluentValidation.WebApi package for validation of client inputs.
Below is my model class code which has C# property named "IsPremium". This same property has json name "isLuxury" for all the clients.
[Serializable, JsonObject, Validator(typeof(ProductValidator))]
public class Product
{
[JsonProperty("isLuxury")]
public bool? IsPremium { get; set; }
}
And my validator class looks like:
public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.isPremium).NotNull();
}
}
So for a request like: http://localhost:52664/api/product
Request body:{ "isLuxury": "" }
I get following error:
{
"Message": "The request is invalid.",
"ModelState": {
"product.isPremium": [
"'is Premium' must not be empty."
]
}
}
Fluent here is picking C# property name which makes no sense to the client as it knows it as "isLuxury". How can i force fluent to pick names from json property and not from c# property to give better validations like "'isLuxury' must not be empty."?
If not possible, i will have to rename all my C# properties to have same name as these json exposed to all the clients. Please suggest if you have any other better way to solve this problem.
There is no way to debug Fluent Validator code with Visual Studio tools. You need to comment the specific part of code (RuleFor) that you want to test. Keep doing it until all rules are tested.
FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.
FluentValidation is an open source validation library for . NET. It supports a fluent API, and leverages lambda expressions to build validation rules.
Modify the validator class with the OverridePropertyName
method
public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.isPremium).NotNull().OverridePropertyName("isLuxury");
}
}
Referring: https://github.com/JeremySkinner/FluentValidation/wiki/d.-Configuring-a-Validator#overriding-the-default-property-name
Alternatively you can call the WithName
method which does a similar thing. If you want to completely rename the property, I'd use the OverridePropertyName
method.
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