c# - How to create a custom FluentValidation PropertyValidator with specific validation error messages? -
i have several different classes name property of type string, rules validating name in each case same, e.g. must not null, between 1 , 32 characters, must not contain invalid/symbol characters etc. - idea.
i using fluentvalidation library validation. new it, i've seen far. started creating abstractvalidator<t> derived validation classes each class in object model validate properties. realized duplicating code validate name properties of various classes, decided create namevalidator custom property validator (i.e. custom propertyvalidator derived class). intent encapsulate 4 or 5 pieces of repetitive name validation logic in 1 place.
what don't solution (based on novice understanding) can't specify different, specific validation error message based on criteria validation fails because error message has defined in constructor , passed on base class. in other words, validation error message tied class type, not runtime logic within isvalid(...) override. example, if name long, i'd provide specific message saying such, not compound message says validation failed 1 of dozen different possible reasons , let user figure out 1 real culprit. perhaps possible somehow , i'm missing it, or perhaps property validator not intended support notion of multiple types of validation.
the next approach considered create namevalidator class derives abstractvalidator<string> , uses various rulefor statements of form: rulefor(name => name).foo(...) etc. facilitates defining specific validation error messages. however, "feels wrong" because abstractvalidator<t> intended validating object whereas propertyvalidator intended validating properties. thoughts/advice on validity (or otherwise) of approach appreciated.
so question recommended way of encapsulating various pieces of property validation logic in reusable way using fluentvalidation library, while maintaining ability provide specific validation error messages describing precisely why failed validation?
if me, use namevalidator : abstractvalidator<string> approach. fact name conforms many requirements makes object in own right.
also semantically, propertyvalidator used represent single type of constraint not single property of object
Comments
Post a Comment