Data Validation in MVC - model-view-controller

Suppose i have a 'View' for filling up form for renting a DVD , as per MVC architecture , either of 'Controller' or 'Model', who is supposed to validate the form data?
Thanks

You validation should be in Model section of MVC.
As models have various fields, only models can know what combination of inputs make that model valid. It's not just about whether a field is blank, or the input of that field matches some pattern, but sometimes this is a combination of field inputs, or the model's relationship to other models that determine the valid state.

All 3 are usually involved in the validation process if you follow the typical flow.
The model defines validation attributes such as the required or stringlength attributes. The controller checks the validation state of the model via ModelState.IsValid and makes decisions accordingly. The view may additional provide client-side validation for those same attributes. Don't rely solely on js to validate the form.

My suggestion would be to validate in the view with some form of validation binding, and then again in the model before persisting to any data store.

Related

Cakephp one model different form validation

I have a model name "User", their I added a validation for login. But I need to validate registration page also. Fields for both forms are different.
Can someone please tell me how to manage different form validation with 1 model.
You can validate as many fields as you want inside your User model, it does not matter in which View or in which form you input them.
So just add the fields from your registration page to the User's $validate inside your User model.
If all forms share similar fieldnames but require different validation rules you can use:
http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
If the duplicate fields validate the same on all forms you can just add them all to the Model, it will only validate the ones present on the form.
Remember to NOT use 'required' => true, setting this key to true will make the field always required and it has to be present in the data array even if it's not on your form

ASP.NET MVC 3 Pattern for dynamic validation attributes including client side

My validation requirements for a the fields in a form are contained in an external table so that they can be updated without altering and rebuilding the code.
I have approximatley 100 fields with a mixture of validation requirements - range, required, regular expression and dependency on other fields. One example is date range validation. A date of birth field requires a date range which is between -10 years and -50 years of the current date.
I have read around the subject but have not identified a pattern for the complete solution.
I am using Visual Studio 2010 with MVC 3 and Entity Framework.
Any help with this would be gratefully received. Thanks in advance.
In a simple level I think you can still use the built-in Data-Annotations validation attributes to does the validation and for that you should map the validation rules stored in the table to the attributes.
I think all you have to do is create a custom model validation provider by inheriting the class ModelValidatorProvider. This class contains a single method called GetValidators that returns the collection validators for that model.
You have to implement the GetValidators method and in there you have to make a database call to get the validation rules for the model from the database (or from cache?) and convert them into ModelValidators. You could still use the built-in DataAnnotationsModelValidator to do the validations.
I would suggest you to look into the source code of DataAnnotationsModelValidatorProvider that will give you all the information. In that class what they are doing is basically iterating all the validation attributes applied to the model properties and converting them into ModelValidators through adapters and factories. In your case instead of attributes they are stored as records in tables and I don't think much work will be there.

Custom Data Annotation Attribute using Metadata

My requirement is to create a custom data annotation attribute for my project. The requirement is to validate the min/ max length of a specific product from the database, which will be retrieved from the database using the ProductID. I have a dynamic page for each product where there are two fields called max length & min length. User inputs the values in these two fields which needs to be validated from the database. Product table contains all the products & one will be selected by passing a productId.
Please suggest some pointers to implement the above.
Thanks in advance.
This validation you can do only in the server side and not in client, so I see two options.
Remote Validation - You can use remote validation when you want to perform the validation and show the error message through ajax.
IValidatableObject - By implementing this interface in the class you can do both the validations at the same time and return all the validation error messages as a collection. By this way the validation will happen after the form is normally submitted.

How to use CakePHP validation without having to define model validation rules?

I have a contact form that doesn't use a model. What's the best way to validate its data?
Should I use cake's automagic goodness and have it create a dummy model on the fly a pre-defined dummy model that validates the data according to the rules I add on the fly or is there a better way?
From my experience, it has always been that you create a model for situations like these, and then set:
var $useTable = false;
in the model. You don't have to do it "on-the-fly". It's just a model with validation rules, without an associated table.
Here's a link that should help you with this.

Model Data Type versus View Control

I have having a little trouble wrapping my head around the design pattern for MVC when the data type of the model property is very different than what I wish to display in a form. I am unsure of where the logic should go.
Realizing that I am not really sure how to ask the question I think I will explain it as a concrete example.
I have a table of Invoices with a second table containing the InvoiceDetails. Each of the InvoiceDetail items has an owner who is responsible for approving the charge. A given invoice has one or more people that will eventually sign off on all the detail rows so the invoice can be approved. The website is being built to provide the approval functionality.
In the database I am storing the employee id of the person who approved the line item. This schema provides me a model with a String property for the Approved column.
However, on the website I wish to provide a CheckBox for the employee to click to indicate they approve the line item.
I guess my question is this -- how do I handle this? The Model being passed to the View has a String property but the form value being passed back to the Controller will be of the CheckBox type. I see two possible ways...
1) Create a new Model object to represent the form fields...say something like FormInvoiceDetails...and have the business logic query the database and then convert the results to the other type. Then after being submitted, the form values need to be converted back so the original Model objects can be updated.
2) Pass the original InvoiceDetails collection to the View and have code there create render the CheckBox based on the value of the String property. I am still not sure how to handle the submission since I still need to map back the form values to the underlying database object.
Maybe there is a third way if not one of these two approaches?
To make the situation a bit more complicated (or maybe it doesn't), I am rendering the form to allow for the editing of multiple rows (i.e. collection).
Thanks for any insight anybody can provide.
You need a ViewModel, like #Justn Niessner suggests.
Your controller loads the complete model from the database, copies just the fields it needs into a ViewModel, and then hands the ViewModel off to the view for rendering.
I'd use Automapper to do the conversion from Model to ViewModel. It automates all the tedious thingA.x = thingY.x; code.
Here is an additional blog post going over in detail the use of ViewModels in the Nerd Dinner sample.
I believe what you are looking for is the ViewModel.
In cases where you are using a ViewModel, you design the ViewModel to match the exact data you need to show on your page.
You then use your Controller to populate and map your data from your Model in to your ViewModel and back again.
The Nerd Dinner ASP.NET MVC Example has some very good examples of using ViewModels.

Resources