|
1 | 1 | # PosInformatique.FluentValidation.Json |
2 | | -PosInformatique.FluentValidation.Json is a library based on FluentValidation to validate JSON object for the Web API. |
| 2 | +[PosInformatique.FluentValidation.Json](https://www.nuget.org/packages/PosInformatique.FluentValidation.Json/) |
| 3 | +is a library based on FluentValidation to validate JSON objects for the Web API. |
| 4 | + |
| 5 | +By default, when using the [FluentValidation](https://www.nuget.org/packages/FluentValidation) |
| 6 | +library to validate an object, the property name (or related display name) are used in the error message. |
| 7 | +This can be useful for functional validation to display to users on the views of the application. |
| 8 | + |
| 9 | +But when you perform some validations in a Web API context, on JSON DTO objects, |
| 10 | +using C# property name does not help developers to indicate which properties are invalid. |
| 11 | +Specially if the C# property name is differents of the JSON property name associated. |
| 12 | + |
| 13 | +For example, imagine you have the following JSON object that represents a product: |
| 14 | + |
| 15 | +```json |
| 16 | +{ |
| 17 | + "description": "Chicken adobo", |
| 18 | + "price": 10 |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +This JSON object is mapped to the following C# class, using `[JsonPropertyName]` attributes |
| 23 | +to define the JSON property names. |
| 24 | + |
| 25 | +```csharp |
| 26 | +public class Product |
| 27 | +{ |
| 28 | + public Product() |
| 29 | + { |
| 30 | + } |
| 31 | + |
| 32 | + [JsonPropertyName("category")] |
| 33 | + public ProductCategory? Category { get; set; } |
| 34 | + |
| 35 | + [JsonPropertyName("description")] |
| 36 | + public string? Description { get; set; } |
| 37 | + |
| 38 | + [JsonPropertyName("price")] |
| 39 | + public decimal Price { get; set; } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +If you want to validate the C# `Product` class, you have to create a validator |
| 44 | +which inherit from the `AbstractValidator<T>` class. |
| 45 | + |
| 46 | +```csharp |
| 47 | +public class ProductValidator : AbstractValidator<Product> |
| 48 | +{ |
| 49 | + public ProductValidator() |
| 50 | + { |
| 51 | + this.RuleLevelCascadeMode = CascadeMode.Stop; |
| 52 | + |
| 53 | + this.RuleFor(p => p.Description).NotNull().NotEmpty(); |
| 54 | + this.RuleFor(p => p.Price).GreaterThan(0); |
| 55 | + this.RuleFor(p => p.Category).NotNull().SetValidator(new ProductCategoryValidator()); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +public class ProductCategoryValidator : AbstractValidator<ProductCategory> |
| 60 | +{ |
| 61 | + public ProductCategoryValidator() |
| 62 | + { |
| 63 | + this.RuleFor(p => p.Name).NotEmpty(); |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +When performing the validation of inside a ASP .NET MVC API application |
| 69 | +the following JSON problem is returned by default: |
| 70 | + |
| 71 | +```json |
| 72 | +{ |
| 73 | + "value": { |
| 74 | + "title": "One or more validation errors occurred.", |
| 75 | + "errors": { |
| 76 | + "Description": [ |
| 77 | + "'Description' must not be empty." |
| 78 | + ], |
| 79 | + "Price": [ |
| 80 | + "'Price' must be greater than '0'." |
| 81 | + ], |
| 82 | + "Category.Name": [ |
| 83 | + "'Name' must not be empty." |
| 84 | + ] |
| 85 | + } |
| 86 | + }, |
| 87 | + "statusCode": 400, |
| 88 | + "contentType": "application/problem+json" |
| 89 | +} |
| 90 | +``` |
| 91 | + |
| 92 | +Here, because we expose this JSON content to developers, we preferred to |
| 93 | +have the JSON property name path in the errors messages. |
| 94 | + |
| 95 | +This the main goal of this library to return the following JSON result instead: |
| 96 | + |
| 97 | +```json |
| 98 | +{ |
| 99 | + "value": { |
| 100 | + "title": "One or more validation errors occurred.", |
| 101 | + "errors": { |
| 102 | + "description": [ |
| 103 | + "'description' must not be empty." |
| 104 | + ], |
| 105 | + "price": [ |
| 106 | + "'price' must be greater than '0'." |
| 107 | + ], |
| 108 | + "category.name": [ |
| 109 | + "'name' must not be empty." |
| 110 | + ] |
| 111 | + } |
| 112 | + }, |
| 113 | + "statusCode": 400, |
| 114 | + "contentType": "application/problem+json" |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +## Installing from NuGet |
| 119 | +The [PosInformatique.FluentValidation.Json](https://www.nuget.org/packages/PosInformatique.FluentValidation.Json/) |
| 120 | +library is available directly on the |
| 121 | +[](https://www.nuget.org/packages/PosInformatique.FluentValidation.Json/) |
| 122 | +official website. |
| 123 | + |
| 124 | +To download and install the library to your Visual Studio unit test projects use the following NuGet command line |
| 125 | + |
| 126 | +``` |
| 127 | +Install-Package PosInformatique.FluentValidation.Json |
| 128 | +``` |
| 129 | + |
| 130 | +## How it is work? |
| 131 | + |
| 132 | +This library is really easy to use and just required to change the `ValidatorOptions.Global` configuration. |
| 133 | + |
| 134 | +To use JSON property names when validating a DTO class, just call the `UseJsonProperties()` at the startup of the application. |
| 135 | + |
| 136 | +For example, in ASP .NET application just call the `UseJsonProperties()` method at the initialization of the ASP .NET infrastructure: |
| 137 | + |
| 138 | +```csharp |
| 139 | +public static void Main(string[] args) |
| 140 | +{ |
| 141 | + var builder = WebApplication.CreateBuilder(args); |
| 142 | + |
| 143 | + ValidatorOptions.Global.UseJsonProperties(); |
| 144 | + |
| 145 | + var app = builder.Build(); |
| 146 | + |
| 147 | + // Configure the HTTP request pipeline. |
| 148 | + app.UseAuthorization(); |
| 149 | + |
| 150 | + app.MapControllers(); |
| 151 | + |
| 152 | + app.Run(); |
| 153 | +} |
| 154 | +``` |
| 155 | + |
| 156 | +And **THAT ALL !!**. |
| 157 | + |
| 158 | +Next, you use your own validation strategy depending of the context usage. |
| 159 | +For example, if you ASP .NET Core to create an Web API, you can use the following code |
| 160 | +and returns an error as JSON problem format: |
| 161 | + |
| 162 | +```json |
| 163 | +[ApiController] |
| 164 | +[Route("[controller]")] |
| 165 | +public class ProductController : ControllerBase |
| 166 | +{ |
| 167 | + private readonly IValidator<Product> validator; |
| 168 | + |
| 169 | + public ProductController(IValidator<Product> validator) |
| 170 | + { |
| 171 | + this.validator = validator; |
| 172 | + } |
| 173 | + |
| 174 | + [HttpPost] |
| 175 | + public IResult Post(Product product) |
| 176 | + { |
| 177 | + var result = this.validator.Validate(product); |
| 178 | + |
| 179 | + if (!result.IsValid) |
| 180 | + { |
| 181 | + return Results.ValidationProblem(result.ToDictionary()); |
| 182 | + } |
| 183 | + |
| 184 | + return Results.Ok(); |
| 185 | + } |
| 186 | +} |
| 187 | +``` |
| 188 | + |
| 189 | +Do not hesitate to read the |
| 190 | +[FluentValidation ASP .NET Integration](https://docs.fluentvalidation.net/en/latest/aspnet.html) |
| 191 | +documentation for more information. |
| 192 | + |
| 193 | +## JSON serialization library |
| 194 | +This library use the JSON property names specified by the `[JsonPropertyName]` attributes |
| 195 | +with the Microsoft `System.Text.Json`. |
| 196 | + |
| 197 | +This library **DO NOT** use the property names specified by the `[JsonProperty]` attributes |
| 198 | +of the `Newtonsoft.Json` library. |
| 199 | + |
| 200 | +## Library dependencies |
| 201 | +- The [PosInformatique.FluentValidation.Json](https://www.nuget.org/packages/PosInformatique.FluentValidation.Json/) library |
| 202 | +target the .NET Standard 2.0 and can be used with various of .NET architecture (.NET Core, .NET Framework,...). |
| 203 | + |
| 204 | +- The [PosInformatique.FluentValidation.Json](https://www.nuget.org/packages/PosInformatique.FluentValidation.Json/) library |
| 205 | +use the 4.6.0 version of the [System.Text.Json](https://www.nuget.org/packages/System.Text.Json/) NuGet package |
| 206 | +and can be used with old projects that target this library version and earlier. |
0 commit comments