Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fluentvalidation error message contains c# property name and not client side json property name?

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.

like image 442
Sahil Sharma Avatar asked Aug 08 '16 13:08

Sahil Sharma


People also ask

How do you debug fluent validation?

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.

What is fluent validation?

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.

Is fluent validation open source?

FluentValidation is an open source validation library for . NET. It supports a fluent API, and leverages lambda expressions to build validation rules.


1 Answers

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.

like image 111
Sahil Sharma Avatar answered Sep 25 '22 20:09

Sahil Sharma