MVC2 DataAnnotations with Server-side validation - 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.

Related

Spring best practice to separate model from view in controller and jsp?

Is it a good practice to use Spring Controller class(with #ModelAttribute) and the jsp to prepare model at the same time or the model has to be prepared only by Spring and the view from the jsp?
The idea comes from this topic . I have a Controller class:
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, params = "mode=create")
public ModelAndView showCreatePage(#ModelAttribute("createForm") ApplicationCreateForm form)
{
return customMethod("some string");
}
and in my jsp I have:
<jsp:useBean id="createForm" scope="request" class="com.example.ApplicationCreateForm"/>
I do not need to populate the form with the information to be present to the user all fields are empty.
So from what I uderstand I have been declared ApplicationCreateForm bean twice, with the same scope - request.
Is it a good design practice to use both at the same time? Is there a reason for that? Does the second declaration(in jsp) give me more power, for example to override the model or it is complete unnecessary? Does the second declaration overrides the first one when both are present?
There are many things wrong with this implementation.
Is it MVC?
If JSP know about Model, why do we need controller. Lets remove the routing engine and use JSP directly to consume Model. But then the application will be monolithic. I believe you do not want that. We have two major flavours of MVC. In both, controller is the front facing object. It receives the command, interprets it, works with data layer and gets Model. If required the Model gets converted into a viewModel and then this object is passed to the view.
Why viewModel?
Say we are implementing paging on screen. We are showing list of persons. Person is your model here but your view also need to know page number, page size etc. Your model thus may not fit directly in this case.
Say we need data from multiple tables to shown on screen. This data is related in some way. Now will you pass separate model objects to view and let it do all the business logic? Ideally no.
Should not the design support DTO or ViewModel or Commands and Queries?
We want our application to be designed properly. As stated above we need to send data to view or clients (REST) after processing. Processed data may not map to you domain until unless we are just creating a CRUD stuff. What if you want to implement CQS or CQRS?
Where is separation, where is SOLID?
If my view is performing business logic then where is 'S'? If view knows about model and need to be changed in slightest of changes in model then where is 'O'?What if I want to separate queries from command (CQS) and scale the two things separately?
To conclude I would say, yes you can do this but it is not good if you are developing a decent size application or you think it will eventually be one. I have seen people using model entities starting from ORM, to controller to view. It will work but the question is do you want a monolithic and tightly coupled application. As per my experience the presentation logic (view) has very different logic and need of data in comparison of controller and same goes for your data access layer.
I think you should prepare your model fully in spring controller. Then view should be as passive as possible, ie. only showing model attributes received from controller while having no further knowledge about application logic. This approach gives you clean separation of concerns and you view is as independent as possible and can be easily switched for different view technology - eg. thymeleaf or freemarker templates. The whole idea of MVC is to separate presentation layer and by leaking business logic to view you create unnecessary dependencies.
Your view should be as simple as possible, as the logic leaked to view makes it very hard to test and reuse. On the other hand, if your logic is nicely separated, you can test it easily and reuse it easily. Ideally, business logic should be completly independent on web environment.
By defining you are creating tight coupling between your view and class com.example.ApplicationCreateForm, using spring mvc you achive loose coupling between your controllers, view and model it might happen that you change you model name but you still have same properties in it which might be enough for view, in above case you will need to update your view but it won't be required in case you are using Spring MVC.
Since spring comes with the concept of making things loosely coupled to make your code more testable, you should always keep in mind that separation of concern is your priority. So it is always the best practice to prepare your model fully in Controller, not in views.
Keep thing simple , make your controller responsible for preparing your model, and keep your views to display the model only.
So, a big NO to your question. The second declaration isn't going to make you powerful, rather help you to be tied up.

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.

Why use fluentvalidation instead of ASP.NET MVC 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.

Simple MVC for Java EE Web Applications?

One of the goals of the MVC approach to web development is to separate out the model, view, controller.
Lets say in a Java EE Struts like environment, you associate the Struts Action with the controller, a Java bean with the model, and JSP and/or ActionForm with the View.
My question, where do you tend to perform any logic to populate data on the JSP. It seems bad practice to put any kind of logic or processing in the view ActionForm and very bad to put any kind of logic in the JSP.
Do you include a "Manager" class to manipulate the data in the View Form before it is display ed to the user.
Here is one simple example. You take First Name, Last Name out of the database and then you need to pretty the format (convert all upper case string to Mixed case). Would the logic to manipulate that string before it gets to the JSP view, add that logic in a manager class?
If it's logic that is only concerned with the view (in your example, making the data look "pretty"), then I would put it in the View. If, however, you would be later saving the modified data, then it should be in the business layer. In general, though, I tend to keep a layer between the View and the Control (your Manager class) that is only concerned with display issues and high level validation of input, but not complex business rules (ensure that very bad data never reaches the business tier).
This very much depends on what framework you're using. I think this kind of thing should be done in the view, but exactly how you would go about that will vary.
If you're using a JSP it might make sense to write a custom tag library to do what you want - so it's separate from the actual HTML but still within the 'view'.
So, you would have something like:
<td><mytag:mixedCase value="${user.firstname}" /></td>
Etc.
For simple presentation concerns such as uppercasing a string, I would put it in the JSP. For more complex business logic, I would put it in the model class. You don't want to be cluttering your controllers with business logic. Another advantage of putting it in the model is that it can be unit tested.

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