tags:

views:

35

answers:

2

I'm trying to avoid double up on my validation and want to know if MVC data annotation validation can be trusted as 'server side validation'.

I've read several posts saying I should validate again in the business layer but I'd rather avoid doubling up the same validation.

Should I ignore data annotations all together and have my business layer do all server side validation which I can then pass on the the UI?

+1  A: 

It's client-side validation that can't be trusted -- this means javascript. Your MVC code is fine (if the validation is in C#, it's most certainly server-side) and the results of your validation can be trusted. Whether you also want to perform validation in your business layer is up to you.

Kirk Woll
A: 

I would say it depends on what you mean by "business layer." If it's logically separated code running in the same process, then I imagine you can trust the validation that's being done in the presentation layer (as long as it's server-side validation).

However, if the business layer is perhaps abstracted behind a service of some kind, or for whatever reason running as a separate process or on a separate server, then I'd solidify that separation by treating the presentation layer as a client and re-validating in the business layer. (The idea being that such separation is generally done when the intent is for multiple clients, perhaps written by multiple developers, to share that business layer. So you'd want to treat them as you would any client-server access.)

Basically, any time a single "application" receives input, validate it. If it's coming from an end user's browser, validate it. (Client-side validation isn't really "validation" so much as a nice feature to make the UI better and lessen the strain on server resources.) If it's coming from another internal application, validate it.

If you intend to later break apart the layers into multiple internal services, then you can go ahead and put in that validation now just for good measure, assuming it doesn't represent a significant performance hit. That is, if it's more comfortable to treat the layers as completely separate and maintain as strict a separation of concerns as possible. Generally, objects should internally validate themselves anyway. So if you're going for a highly object-oriented approach in your code then you'll want to maintain that.

David