How to replace standard DataAnnotations error messages

后端 未结 3 1816
小蘑菇
小蘑菇 2021-01-18 03:56

I\'m using System.ComponontModel.DataAnnotations to validate my model objects. How could I replace messages standard attributes (Required and StringLength) produce without p

3条回答
  •  独厮守ぢ
    2021-01-18 04:32

    For ASP.NET Core validation, refer to this page, where it explains how to set it up using the service engine:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddDataAnnotationsLocalization(options => {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                    factory.Create(typeof(SharedResource));
            });
    }
    

    Otherwise (WPF, WinForms or .NET Framework), you can use reflection to interfere with the DataAnnotations resources and replace them with your own, which can then be automatically culture-dependent on your app's current culture. Refer to this answer for more:

    void InitializeDataAnnotationsCulture()
    {
      var sr = 
        typeof(ValidationAttribute)
          .Assembly
          .DefinedTypes
          //ensure class name according to current .NET you're using
          .Single(t => t.FullName == "System.SR");
    
      var resourceManager = 
        sr
          .DeclaredFields
          //ensure field name
          .Single(f => f.IsStatic && f.Name == "s_resourceManager");
    
      resourceManager
        .SetValue(null, 
          DataAnnotationsResources.ResourceManager, /* The generated RESX class in my proj */
          BindingFlags.NonPublic | BindingFlags.Static, null, null);
    
      var injected = resourceManager.GetValue(null) == DataAnnotationsResources.ResourceManager;
      Debug.Assert(injected);
    }
    

提交回复
热议问题