0

I have an entity being used in many parts of my application. I need to add validation to one of its properties. The problem is that I do not need to validate this property in every part of my application.

I considered using a custom attribute, but then I would not be sure how to bypass the validation in (because it does not depend on other property, it really depends on the part of the application I am using it).

I considered using an interface and have two implementations - one with this attribute, one without. But there is too much coupling in my application and that may be too much work.

Eventually, I could just create a static class to validate it. But I am wondering if there would be a more MVCish option? Thanks!

  • A derived type could hide the property (`new`) and add the attribute. – asawyer Oct 09 '14 at 18:35
  • MVC has nothing to do with validation. MS MVC framework supports the validation by attribution to make it easier for developers. In your case, just a validator class should be the simple option and seems like you're doing it already. – AD.Net Oct 09 '14 at 18:40
  • I think the "easy" way can be found here http://stackoverflow.com/a/10896355/1370442 – Luke Baughan Oct 09 '14 at 18:41
  • Either use view models, so you can have one class with the validation that used in your views and then your entity without said validation that can be used when it's not necessary to be validated, or follow @asawyer's advice. – Chris Pratt Oct 09 '14 at 19:04

1 Answers1

2

Specification Pattern is a good option for this problem. You can create a specification class to validate your property and use this specification to validate the property where do you want to really perform the validation.

Below some C# libraries for this pattern:

giacomelli
  • 7,287
  • 2
  • 27
  • 31