Why use fluentvalidation instead of ASP.NET MVC validation - validation

In which circumstances would you choose FluentValidation (FV) over the ASP.NET MVC 3 way?
What are the advantages of FV over MVC? I realise that with the latter we have to write much more code and can litter the code with Data Annotations. Moreover, it would seem to be easier to write custom validation using FV than MVC. However, with MVC it is possible to make use the data annotation and plug jQuery validation in.
So what in your view would make you choose one over the other? Are there circumstances where you would even use both?

Fluent validation is one way of setting up dedicated validator objects, which you would use when you want to treat validation logic as separate from business logic. The aspect-oriented programming (AOP) paradigm enables separation of cross-cutting concerns within a system, and validation is one such concern. Separating validation helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.
MVC annotation-driven validation is a very 'cheap' way to get some basic validation into an application, without going to the hassle of creating dedicated validator objects, creating a validation system which organizes them and plugging it all together. It's very easy to set up, but can make your domain objects less clean.
For small systems where all the validation logic can be handled using annotations, I would recommend just using annotations, because they're so easy to set up. For larger, more complex systems, I would recommend separating the validation concern using validator objects.
I personally like to use both approaches: add validation attributes to ViewModel classes (which means the annotations don't clutter up my domain objects), as well as having dedicated validator objects within my domain layer. This is a small amount of duplication, but using annotations is so quick and easy, I find it worth the extra maintenance cost.

Related

Is Data Annotations validation a good practice?

Is using data annotations validation like in MVC really a good practice? wouldn't it pollute my POCO based domain model? Should I care about it or it is just another slip for Microsoft that I should overlook?
I wouldn't exactly say pollute. I mean let's be honest.. Data Annotations barely take up any space at all, and they're super easy to find since they are decorated over their respected properties.
But in terms of separation of concerns.. the models/classes purpose is to perform business logic. Most, if not all, of the stock data annotations deal with business logic. However, this can be subjective/opinion based because some developers perform business logic in the controller and/or the view.. depending on the situation.. so it can vary.
So.. in my opinion I think data annotations are very good practice when it comes to the MVC world. The more that a developer can separate the responsibilities of the Model, View, and Controller without intertwining them.. the more maintainable the code will be in the future.
I hope this helps.

Where to implement cross-entity-validation?

I have a project where the data-model and business-layer are located in two different modules. Of course, the bussiness-module has a dependency to the model-module. The entity-validation is implemented through java-validation-api annotations.
I'm wondering where I should implement the cross-entity-validation (business validation, where the relations between different entity types are validated). Currently I see the follwing options:
Create custom javax.validation.ConstraintValidators and associated annotations. Problem is, that the validator would need access to the business-services, i.e. to retrieve related entities, but the model-module should not have a dependency to the business-module.
Implement cross-entity-validation in the business-services persist/merge-methods (i.e. by using interceptors). That would be possible, but the cross-entity-validation is seperated from the entity-validation and I would like to have only one place for validation.
Which option is preferable? Are there any better suggestions?
Thanks,
Sebastian
From the ideological point of view approach 1. is better. Bean Validation is working at the level of Model (in Model-View-Controller) and it is nothing wrong if Model part talks to database. So, for instance, you can create DAOs, which can be used both by service leayer and Model validators in order to avoid code duplication.
Interceptors are also good place to validate something, but you will not be able to use full power and automaticity of Bean Validation. Probably you will need to call validate method on your model objects by hand, throw ConstraintViolationException where needed, etc. Doable, but a little bit of work. In addition some validation probably will be left in Model, so, as you've pointed out, there would be more then one place, where validation is going on.
So I would move necessary DB code to separate layer and go with option 1.

MVC2 DataAnnotations with Server-side validation

How do you validate an entity containing DataAnnotations without using the MVC library? Using Model.IsValid is fine when you're within the Presentation layer, but what about when you want to ensure the model is valid in the Domain/Business layer? Do I need a separate validation framework, or is there an easy way I'm missing?
Thanks for any help,
Mark
I suppose you mean ModelState.IsValid by Model.IsValid, right? Well, DataAnnotions don't depend on MVC at all, so you can always use the IValidatableObject interface.
Or perhaps the Validator class will be more appropriate, by using Validator.ValidateObject(object, ValidationContext).
I wrote my validation logic using plain c#, my business layer contains these validations and I use try and catch blocks throughout business layer. The presentation layer catches these custom exceptions so errors are shown on screen to the user. I only kept basic validation inside the data annotations e.g. [Required] mainly for ajax calls and to notify users to enter data in non nullable fields, that way my business logic remained in my middle tier, it remained consistent, it remained in only one place which I can refer to.

How best to modify my model in Spring MVC if I care about IOC

I am building an application using Spring MVC. I want to make certain changes to my Model for every Controller in the application. In particular, I want to insert certain extra data into the model which will be present for all pages of the application.
I could do this several ways: just add the data at the end of every Controller, use a subclass of Model that adds my extra data, use a subclass of ModelAndView that wraps my Model, use a subclass of VelocityView that wraps the Model before using it... I'm sure there are other options.
But I have an "elegance" constraint: I don't want to write code in each and every Controller, I want this behavior defined in one-and-only-one place. Ideally, it would be controlled by my IOC bean config file.
Does anyone have a recommendation of how to achieve this elegantly?
Aspects are a good approach, but Spring MVC makes it even easier -- you can define a HandlerInterceptor that will be called before or after every time a request is handled. In the HandlerInterceptor postHandle method (in your class that implements the HandlerInterceptor interface) you can add your data to the ModelAndView. You define which handlers should be intercepted in your config file.
You could take a look at using Aspects. Spring even has an AOP extension that you could use.
In brief an aspect would allow you to define code once that would then get "woven" into your classes either when you compile the classes or when they are loaded by the classloader. It's relatively advanced stuff and isn't the most intuitive thing for new programmers to pick up, but it's intended to solve exactly the problem you're referring to.
I might be wrong, but I suspect that you may have described your requirements incorrectly.
You seem to be saying 'I want certain data to be added to my model, for all controllers'.
I suspect that you mean 'I want certain data to be available for all views'.
If my suspicions are correct, then adding the data to you model is polluting your model and violating the single responsibility principle. This is especially true if the same data is to be added to several models. Be careful that you are not just using your model as a convenient 'carrier' of the data - where the data doesn't really have anything to do with the model.
Admittedly, I'm not completely familiar with the Spring MVC way of doing things, but a more detailed example of what you're trying to achieve may allow for a more informed discussion.

MVC - where to implement form validation (server-side)?

In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?
From Wikipedia:
Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.
Thus, model - it holds the application and the business rules.
I completely agree with Josh. However you may create a kind of validation layer between Controller and Model so that most of syntactical validations can be carried out on data before it reaches to model.
For example,
The validation layer would validate the date format, amount format, mandatory fields, etc...
So that model would purely concentrate on business validations like x amount should be greater than y amount.
My experience with MVC thus far consists of entirely rails.
Rails does it's validation 100% in the Model.
For the most part this works very well. I'd say 9 out of 10 times it's all you need.
There are some areas however where what you're submitting from a form doesn't match up with your model properly. There may be some additional filtering/rearranging or so on.
The best way to solve these situations I've found is to create faux-model objects, which basically act like Model objects but map 1-to-1 with the form data. These faux-model objects don't actually save anything, they're just a bucket for the data with validations attached.
An example of such a thing (in rails) is ActiveForm
Once the data gets into those (and is valid) it's usually a pretty simple step to transfer it directly across to your actual models.
The basic syntax check should be in the control as it translates the user input for the model. The model needs to do the real data validation.

Resources