| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ValidationLocalization.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Linq.Expressions; |
| | | 9 | | using System.Reflection; |
| | | 10 | | using System.Threading; |
| | | 11 | | using FluentValidation; |
| | | 12 | | using MyNet.Globalization.Facade; |
| | | 13 | | using MyNet.Observable.Localization; |
| | | 14 | | |
| | | 15 | | namespace MyNet.Observable.Validation; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Configures FluentValidation to use <see cref="ValidationResources"/> and translated property names. |
| | | 19 | | /// </summary> |
| | | 20 | | public static class ValidationLocalization |
| | | 21 | | { |
| | | 22 | | private static int _configured; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Replaces the global FluentValidation language manager and display name resolver. |
| | | 26 | | /// Safe to call once at application startup. |
| | | 27 | | /// </summary> |
| | | 28 | | public static void Configure() |
| | | 29 | | { |
| | 6 | 30 | | if (Interlocked.Exchange(ref _configured, 1) == 1) |
| | 3 | 31 | | return; |
| | | 32 | | |
| | 3 | 33 | | ValidatorOptions.Global.LanguageManager = new ValidationLanguageManager(); |
| | 3 | 34 | | ValidatorOptions.Global.DisplayNameResolver = ResolveDisplayName; |
| | 3 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Assigns <see cref="ValidationLanguageManager"/> without changing the display name resolver. |
| | | 39 | | /// </summary> |
| | | 40 | | public static void UseValidationResourcesLanguageManager() |
| | 0 | 41 | | => ValidatorOptions.Global.LanguageManager = new ValidationLanguageManager(); |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Resolves property display names from the member name translation key. |
| | | 45 | | /// </summary> |
| | | 46 | | public static string? ResolveDisplayName(Type type, MemberInfo? member, LambdaExpression expression) |
| | | 47 | | { |
| | | 48 | | _ = type; |
| | | 49 | | _ = expression; |
| | | 50 | | |
| | 114 | 51 | | if (member is null) |
| | 3 | 52 | | return null; |
| | | 53 | | |
| | 111 | 54 | | var translated = member.Name.Translate(); |
| | 111 | 55 | | return string.IsNullOrWhiteSpace(translated) ? member.Name : translated; |
| | | 56 | | } |
| | | 57 | | } |
| | | 58 | | |