4

I am working on a project with a lot of models where I need the same validation with localized error messages happen at a couple of different places. Right now I decorate the corresponding properties with

        [RegularExpression(Bla, ErrorMessageResourceType = typeof(Blub), ErrorMessageResourceName = Blablablub)] 
        public int SomeInt { get; set; }

How can I specify a shorthand for this with a custom validation attribute? What I want is something like

        [MyRegularExpressionDecorator] 
        public int SomeInt { get; set; }

Any input is greatly appreciated. Thanks!

Mark
  • 39
  • 5
  • see https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0#custom-validation – rene Jul 13 '21 at 18:14
  • Maybe useful: https://stackoverflow.com/questions/57485326/asp-net-core-2-2-razor-pages-user-input-validation-for-ip-address/57487388#57487388 – rene Jul 13 '21 at 18:20
  • Thanks for the pointers to the custom ValidationAttribute. With this I could create something from scratch where I also implement the entire error handling using IStringLocalizer etc. once more. I was wondering if there is some more elegant way to take advantage of the already implemented functionality regarding localization via ErrorMessageResourceType and ErrorMessageResourceName. Sorry. Should have been more precise in the original question... – Mark Jul 13 '21 at 19:03

1 Answers1

2
public class MyRegularExpressionDecoratorAttribute : RegularExpressionAttribute
{
    public MyRegularExpressionDecoratorAttribute()
        : base("bla") 
    {
        ErrorMessageResourceType = typeof(Blub);
        ErrorMessageResourceName = "Blablablub";
    }
}
Sasan
  • 3,840
  • 1
  • 21
  • 34
  • Works like a charm. Thank you so much @Sasan! Now that I see it spelled out feels like somthing I should have come up myself :) – Mark Jul 13 '21 at 20:08