3

I have a bunch of data classes in my C# project. I need to perform a validation before the processing of the objects of those classes. The classes donot have a common interface. I am trying to formulate some sort of design pattern where I can specify the validations that need to be performed on each field of the class; without having a set of if else type conditions.

I came across the specification pattern, but that did not seem very convincing.

Are there any existing patterns/C# methodologies that I can use?

[Update: I ended up using a combination of the Annotations and the Specification pattern. The basic validations can be done via the annotations. If any special cases occur which cannot be validated via annotations, those validations are written via the specification]

user1542794
  • 137
  • 1
  • 12

3 Answers3

3

You probably want to just use Attributes to specify your validation rules. This is the namespace where all the basic validations exist: ComonpentModel.DataAnnotations. If you want to get fancier, this NuGet package gives you lots of extra attributes: Data Annotation Extensions. Both of these support client side validation with ASP.NET's MVC unobtrusive validation.

Milimetric
  • 13,411
  • 4
  • 44
  • 56
1

Aside from Milimetric's answer you can also look in to Code Contracts. From your question it is not evident if it will fit your needs

Code contracts provide a way to specify preconditions, postconditions, and object invariants in your code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits. Object invariants describe the expected state for a class that is in a good state.

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
0

Take a look at the NCommon library which is a collection of useful patterns around Specifications and Validations.

For more links and information, also see my answer to this post.

Community
  • 1
  • 1
Chris Melinn
  • 2,046
  • 1
  • 17
  • 18