ASP.NET MVC 3 Pattern for dynamic validation attributes including client side - asp.net-mvc-3

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.

Related

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.

Data Validation in MVC

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.

Structuring a model - MVC (PHP)

How should one structure validation, preparation and arrangement (etc) of data before dealing with the DB?
The data I expect to be passed might need to be validated (ex: category books actually exists) or contain conditional values (ex: sale price should only be set if ad = sale) or values that must be converted to ids (ex: category books must be converted to category_id 123).
I imagine that there are numerous ways to go about this like clumping everything together, grouping by field (do validation, prep etc together per field) or separating by action (validation, prep, etc) and field.
Are there any concepts when it comes to this topic just like the concept of MVC exists? Achieving flexibility, ease of maintenance or something like that?
Anything relating to common used components of model?
(I'm not sure if it helps but I'm currently using CodeIgniter / PHP)
In codeigniter, you can use the Form_Validation class with a callback method that you create. http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks.
In your callback method you can check to see if things exist in database, etc.

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.

Can ADO.NET create its own basic validation by reflecting the database structure?

I am now to the stage of adding validation to a simple app for editing a few SQL tables via data-bound controls. I can see that the BindingSource knows the limits of the table's structure: if I enter, for example, letters in a field that should contain only decimals, up pops a DataError exception with the message that you can only enter decimals there.
It seems to me that ADO.NET should be able to use reflection to generate basic validation for all the data-bound fields. But after a lot of Googling, I see only people creating their own validation by column by column.
Can I use ADO.NET's knowledge of the database structure to have it make some of the basic validation for me (e.g. data type, text field length limits)? Do you have some examples?
I'm sad that I've never gotten a good response on this question... but I think I have my answer:
Yes, it should be possible, but no, it hasn't been done yet.
(Maybe someday I'll start a project myself to make a tool which would auto-generate basic validation values for data-bound form fields.)

Resources