views:

77

answers:

2

I want to know the available options for using the "Code Contracts" attributes as the validations rules in ASP.NET MVC 2.

A: 

You could do this by customizing the Runtime Checker.

Although it is possible to tweak Code Contracts into being used as a validation framework, I would advise against it. It is one of the more advanced features to tweak the Runtime Checker and more importantly, not what Code Contracts is made for.

Code Contracts is basically a means of integrating Design by Contract in your project. Although one of its purposes is to validate your code against your class design, it is not a validation framework.

In my opinion, you should use it next to another real validation framework.

Before you start using Code Contracts, I suggest you read the user manual here. It has all the information, including how to customize the Runtime Checker.

KoMet
thanks for your reply, I just shared my thoughts on your answer in the following post.
Sh.Najd
A: 

Yes that is true that the main purpose of "Code Contracts" is to validate my code against my class design but it also describes the valid states of my object.

All I can think of validation scenarios, is of these three types:

  1. Input Validation ( UI Validation )
  2. Domain Validation ( DbC )
  3. Output Validation (Persistence Validation, Ex: NHibernate Validator )

I consider validation as a logical question whether the target object is in a valid state or not.

The DbC has three parts,

  1. the validation rules
  2. the static checker
  3. the runtime checker

The first part ( the rules) is common in all three scenarios of validation. When I tag a property with "Not Null" using "Code Contracts" to validate its design, isn't it ugly to have it tagged "Not Empty" using "System.ComponentModel.DataAnnotations" for MVC (UI Validation) ?

In abstract, the definition of valid states is core and the shared part of validation frameworks and "Code Contracts" provides it, with one extra which is the "Static Cheker" for the domain design (not the I/O).

Sh.Najd
I believe Code Contracts can do more (complex) validations than DataAnnotations. And even so, you do have three separate concerns here. Input validation may have some overlap with Domain Validation ( and even Output Validation ), it doesn't necessarily has to be that way. Seperation of concerns is one reason to keep these three validations separate.
KoMet