Wednesday, July 27, 2011

[Tutorial] Code First with Entity Framework 4.1
Part3: Data Validation

Data validation is a very important subject when developing applications. You have to assure good quality and high integrity of your data for being able to exploit it correctly. You need to avoid storing any corrupt, incomplete or wrong data in your database which will most certainly lead to misbehavior within your applications.

The following example shows how to implement a constraint on the Name property (required / string length between 5 and 20 characters) via Data Annotations.


Validation is automatically done when calling the Save method to persist any changes applied to your objects in memory. But you may as well do it before by calling the GetValidationErrors method.


Lets say when the code above is executed it will fail due to validation errors. In this case error messages will be displayed for each constraint that was not respected. In our example we defined that the Name property should have a minimum string length of 5 characters, but the property only contains 4 characters. Since we did not define a specific error message, a generic error message will be displayed for this validation error.


There are multiple Data Annotations that allow for type validation, format validation, regular expression matching, etc….


No comments: