we are building an ASP.Net MVC application, and we ask ourselve the question where we shoud put the validation logic for incoming data.
We already have the simple validation in place: these are attributes on the viewmodel, like [required], [numeric] , [email] etc. (this is open for discussion too, btw)
But now we have some more input validation: we want to validate if the id’s received from dropdownlists are genuine id’s.
For example: when we receive 91 as a countryid, i have to make sure 91 is a valid countryid and not a value ‘hacked into’ the form by a user. Because if it is not a valid countryid, my datalayer generates an error.
-
Should i place this in the controllers action method, because that
method knows what is right and what is wrong when the data from the request arrives? -
Should i place it in a VacancyValidator (the object is a Vacancy
object) where i put all validation logic for all vacancy related
viewmodels -
Should i place it in the ViewModel because it should know how to validate itself
-
Should i create an attribute which validates the property which i place on the ViewModels property
-
Should i place it in a Vacancy[thisviewmodelsname]Validator where i put all validation logic for this specific viewmodel
Any ideas appreciated….
I would recommend FluentValidation.NET instead of Data Annotations which plays nicely with ASP.NET MVC. It provides a nice syntax for expressing complex validation logic between interdependent properties without writing millions of lines of plumbing infrastructure code (which is what you would have to do if you use Data Annotations and write a custom validator) and also allows you to unit test your validation logic very easily.
There you go – your data layer already handles this validation for you. But if you don’t want to leave it to reach the data layer then you could have a validation rule for this property on the view model. If you follow my previous advice about
FluentValidation.NETyou will already know where to put this rule – in the corresponding validator of your view model.