Search code examples
asp.net-mvcdatabasevalidationnerddinner

How do I get database validation among my rule violations on ASP.NET MVC?


On the NerdDinner example a set of business rules are written to validate the data on a model. Things like empty strings are checked for and by calling modelObject.GetRuleViolations() you can get them all. But there's another layer of validation which is the database. For example, the datetime field is left for validation to the database, which only accepts a string that can be converted into a DateTime object.

The problem I see is that modelObject.GetRuleViolations() never return the violation for datetime. So even when it is correctly prevented from saving the record and the form is shown back specifying there's an error and highlighting the datetime field, there's no specific error message. Is there a way to get the database validation errors among the business rules validation errors?


Solution

  • You need to catch the exceptions thrown by your Data Access Layer, and convert those into calls which update the ModelState to indicate the errors in question. There's not really a good way to do this on a global level, since specific SQL errors will only be able to be interpreted at the time they're called, rather that handled in a generic way.