Where to put validation logic in MVC software architecture - model-view-controller

I am actually starting to learn the mvc architecture.
I'm confused on whether to place my username registration validation logic in model or in controller.
I have some sort of status message that would tell the user whether the new username to register is available or not.
My confusion started because most sources say that it should be in the model because it involves the username data to validate before placing it on the database (rather than checking inputs to the username field). However, the status message should respond immediately prior to the change in the username field by user keypress or change, which lead me to think that it should be in the controller because it involves more on user events.
My concern is not actually on the framework to use but on the standard concept involving MVC. Where do I put the username validation logic based on the conditions/premise above?

As Shikhar says, the actual checking of whether the name is acceptable/available is a Model responsibility. The controller can provide an action that is called by some AJAX on the page, so that as each key is pressed, the text on the page is sent to the dedicated controller action which then validates it through the model (anything that touches the database is Model).
There are a couple of things to consider in the view, such as when the user is typing quickly, you should cancel the previous calls before making the new one as this can get confusing.
Also the controller post action that happens when the user submits the form at the end of their data entry should perform the same validation as the AJAX action did just to avoid race conditions between users.

It should be in the model as you have read yourself. I think you are getting confused between the "validation process" and "validation rules". Validation process will either be in controller on the client side but validation rules are properties of model.

As an addition to #Colin Desmond, a model-instance should never contain 'wrong' data and thus, in my opinion, in an MVC environment should contain validation logic. So that, regardless of the place where an instance of the model is created, it can never be initialized with wrong data and classes that operate on the model instance can rely on its data. The exception is if there is validation logic that is view dependent. View dependent logic (exceptions) should be implemented in the controller.
For example, validation of an email-address should be implemented in the model. However, a model might allow a bank transaction with a negative amount, but view A might not allow a transaction with a negative amount. The logic for this exception should be implemented on the controller.

Related

validate data in controller and model, or just controller?

I have the action contlrSaveText() in controller and the method modelSaveText() in model.
When the data comes from the website to the contlrSaveText(), I check whether the required information is received to save text, i.e. text name, text content etc. Then I call modelSaveText() to actually perform saving text. Do I need to validate data in this method as well or I can expect that controlled already did the job?
A model is only an abstract description, while a controller does the work.
Your model might have a controller on its own that take care of the data and updates the model. But that is technically a controller.
How he works with toward the outside, e.g. another controller that fills data in, is up to you how you define the interface. If your model uses relations or properties that require to be set up by the controller then you have to validate the data before inserting/accepting. But if not, then there is no point in validation and it can be skipped for performance reasons.
If you need to reject invalid data you have to think of a way how to tell the outside what whent wrong so it can respond to the error.
In your example I would go for validation, but that is just my opinion.

MVC question: direct modell <-> view communication - why?

can anybody tell me, why communicates the model direct with the view in the MVC pattern, and why not just throught the controller?
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Sometimes it is too costly to use Controller for simple View/Model communication.
If your view just shows raw data without any operation (filtration, visualization, modification ...) it is easy to forget about Controller.
But this behavior is so abuse-able sometimes it kills all of the advantages of MVC.
And this where MVP comes in:
MVP (Model-View-Presenter) cuts the connection between model and view and every thing pass through man-in-the-middle (Presenter).
The views know of the model and will interact with the model.
If a button is clicked an action message might be sent to a model object in order to get
something done.
If a new value is typed into an entry field an update message might be sent to a model
object in order to give it its new value.
If a value is needed for a display an enquiry message might be sent to a model object in
order to get a value.

What is the best way to handle domain-centric validation while providing a rich UI experience?

My company is developing a GUI application that allows users to query a legacy database system and have the results displayed back to them on the screen (the results just come back in a blob of plain-text). I'm struggling with the best way to structure the interaction between the user interface and the domain layer, especially validation of user input.
Basic Use Case
User selects a query to run from a menu in the application.
The application code displays the data entry form for the selected query.
The user enters the parameters for the query. If a field contains invalid data, it is immediately highlighted in red, and its tooltip text is changed to display an error message (i.e. if you are entering a Person query, and you enter a date of birth in the future, for example, the date of birth field will immediately turn red).
When the user clicks Run Query, the application runs a second validation pass; this second validation pass is required in order to run validation checks that involve multiple fields. If the this validation check passes, and all the fields are valid, the query is sent; otherwise, the user is prompted to fix any remaining errors.
My Current Validation/Error Reporting Strategy
Currently, I'm using domain-centric validation, but the overall design seems messy to me and maybe a little too over-engineered. A brief overview of the current design:
Domain layer: I have one class per query. Every query class contains a collection of IQueryField objects that hold the values entered by the user. Each query class implements a common IQueryMessage interface, which defines (among other things) a Validate method. This method is called to enforce message-level validation rules (i.e. rules that must examine the state of multiple fields at once). The IQueryField interface also defines a 'Valdate' method (among other things). This is to support per-field validation rules.
Per-field validation: To handle the per-field validation and error reporting, the data entry code binds each input control to an IQueryField; whenever the user changes the value of a control, it calls the the corresponding IQueryField's Validate method, which in turn fills a Notification object (just a collection of strings at the moment) with any errors detected in the value entered by the user. The user interface code then checks the Notification object and changes the appearance of the user control to indicate an error condition, if necessary.
Message-level validation: When the user tries to send a query, the application calls the Validate method on the IQueryMessage instance associated with the data entry form (at this point, the data binding code has also ensured all the message's fields have been populated from the input controls on the form, and the per-field validation code has been run). If there are any validation errors, the user interface displays them at the top of the form. If there are no errors, the data entry form is closed and the query is serialized and sent over the network.
Is Something Wrong Here?
I feel like something isn't "right" here. I have a few issues with the current design:
I would like the domain-level validation code to indicate the name of any fields that are in error, bur I don't want to hard-code the UI label captions into the domain classes. One possibility I thought of was to have the domain-level Validate methods generate messages with a field placeholder, such as "%s cannot be in the future", and have the UI code fill in the placeholder with the correct label.
The IQueryMessage and IQueryField interfaces both have a method called Validate. I'm thinking this should be extracted into a separate interface, (IValidatable perhaps), but I wonder if I am making things needlessly complex.
I'm using VB6, so I can't use inheritance in my classes (VB6 supports classes but not inheritance). I can only define and implement interfaces. Because of this, and because of the way my current interfaces are designed, I'm duplicating a lot of boiler-plate code in my implementation classes. I am thinking of solving this with an inversion-of-control approach. For example, I was thinking of defining a single concrete QueryField class, which could be initialized with a collection of IValidationRule instances that define what validation rules to use, then the QueryField.Validate() method would just collect the results of executing each rule. This way, the validation rules can be tailored to each field, but the QueryField class can handle all the common field-related stuff (field name, field length, required/not required checks, etc.).
How Can I Improve This?
I'm interested in any refactoring suggestions and hints on improving the current design. Also, I'm not necessary tied down to domain-centric validation; other suggestions are welcome. The main motivation behind using domain-centric validation was to keep increase encapsulation, and allow query message and field objects to be used in a non-GUI environment, without having to rewrite all the validation logic.
When you initialize a QueryField object, pass a label to it from the GUI. Then it's the UI that is responsible for setting the label name which seems reasonable to me.
I don't think this is necessary.
What you are describing doesn't really sound like IoC but rather just plain old composition. Since you can't even use inheritance this improvement seems to make sense. Generally you want to prefer composition to inheritance anyways. However if you are almost done with the work then I wouldn't bother refactoring this late in the game.

Getting user input from Model Layer

Have a problem following the MVP or MVC design pattern (applies to either one). I can't figure out how to cleanly prompt for user input from the model layer? Depending upon certain values in the model, I may need to prompt the user for input during the middle of a process.
For example, we'll take a hypothetical PO entry process. Say after the user hits a button in the view it calls the presenter passing in the PO details from the view. The presenter then calls the model to validate and insert the new PO into a collection of POs. One of the validation checks in the model is to make sure another PO has not already been entered with the same items. If one has, the app needs to prompt the user to confirm the PO is not a duplicate. The app is currently deep into the model. How do I go all the way back up to the view to retrieve the operator input, then return to the model code where it left off to finish the PO entry process?
In a paper I read on presenter first it was suggested that the presenter had dependencies on the model and on the view and subscribed to events from both the model and the view.
This would mean that you could raise an event from the model at the point where the processing cannot continue. The presenter would handle the event from the model by calling some method on the view (which would prompt the user). The return value from the method on the model would then be returned to the model (an in/out parameter to the event like the EventArguments subclasses used by .NET).
You might want to look at some form of notification interaction between your model and the other components of your UI pattern.
Martin Fowler wrote about it here.
As far as being deep in the model, getting user input, then going back into the model: don't. Your controller is responsible for modifications to your model, and should do the validation before attempting to change your model. This may require separating your validation from your update code.

In MVC, where is the correct place to put authorization code?

In MVC, where is the correct place to put authorization code?
The controller?
The Model?
In the view?
All over the place?
I vote for putting it where it makes sense. Most of my authorization stuff is handled via decorating controller actions (or even some controllers) with the AuthorizeAttribute -- or an attribute derived from it. In a few cases -- like my menus -- I've resorted to putting the authorization check in the view code itself, rather than calculating it in each controller and passing flags down in ViewData. There are a few instances where certain aspects of the model are only available to particular roles and in those cases I've resorted to extending the model with methods that can take the current user and roles and do the check there.
I think authorization is a cross-cutting concern. Should be in one place - an aspect that can be declaratively applied where it's needed.
The Controller!
Your View should only handle user interface and display
Your Model should represent the data in your system.
Your Controller should handle the logic of how the system works.
Authorising a user involves taking the credentials provided from the View, checking them against some sort of authorisation list in the model and then performing a check.
This is done in the controller:
Get user credentials from View
if(compare with user list in model returns match)
authorise users
else
refuse access
If you have to choose between M, V or c, the C is the correct place. But, I recommend an architecture where your app is all contained in libraries and the UI is just a thin veneer. You end up calling down the stack from the Controller, but the code is not in the controller.
In MVC, the Model is just a model, or a "dumb data object", if you will. It is designed to hold state, and should not dictate behavior. The View is for the user to interact with and is also "dumb"; the view handles UI. The controller is where behavior sits, or is the entry point into behavior in the case where the app logic is in libraries. Make sense?
Model.
Controller is just for switching through different ways. View is just for... viewing.
So you should make all authorization codes in the Model layer. Ideally, everything will work just fine. If not, then the controller will take the user to the proper login box.

Resources