Validation with Model Binding against 3rd party library - c#

I want to use class annotations to validate a razor form that collects data for properties of a third party's library class which I cant edit.
Of course I could just make a copy of the class and place the validation annotations on that but this would be ugly and difficult to maintain.
What do people consider best practice for this?

You could use FluentValidation.NET instead of data annotations. It allows you to define validation rules in a separate file. It also allows you to define complex validation scenarios which would be difficult to achieve using the data annotations declarative approach.

Related

Model validation in ASP.NET MVC using Attributes or using IValidatableObject(sel-validating model)

I am learning ASP.NET MVC and as part of Data Annotations 2 approaches are mentioned for performing Model Binding.
**
Attribute based Binding and Validation.
IValidatableObject Interface based self validating model.
**
Is there any advantage to using any one over the other.
When would one go for first approach and when for the second approach?
Use the built in Attributes in most cases. They are relatively reliable for your basic model validation and quick and easy to implement. I would only use IValidatableObject if you have some more complex custom validation that you have to implement.

C# MVC Custom Attributes

I have model based on existing database and I have written metadata class and custom attribute class, Now I want to convert all custom attribute logic into Jquery or Javascript custom function, Please guide me simple or any available free tool for the same.
rcdmk and Scott Selby have provided excellent resources for how to implement the IClientValidatable interface to integrate with jquery unobtrusive validation. As an alternative, if you don't want to maintain javascript versions of your validation logic, you could use the RemoteAttribute class to instruct the unobtrusive validation to perform an ajax request to validate the data (in fact in some cases this would be the only proper way to validate something - such as username availability).
RemoteAttribute Class
How to: Implement Remote Validation in ASP.NET MVC
To this moment, there's not a tool for converting custom validator in c# to custom client side validator in JavaScript [that I know of].
I advice you to look for custom validators already built on the web, like http://foolproof.codeplex.com/. Some of them may have what you need and if you can't find one that suits your requirements, follow some tutorials on how to build your own and, maybe, start your own open source project. Since you needed it, others may need it too.
Some tutorials on how to build your own custom validators may get you where you want:
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC-3
And this is one of my favorite references:
http://anthonyvscode.com/2011/07/14/mvc-3-requiredif-validator-for-multiple-values/
With all this in hand I'm sure you will succeed in create your own client side validators.
You should definitely look at unobtrusive validation in MVC. It adapts MVC to work with Jquery and Jquery validate plugins using data attributes within HTML markup. Once you add a Custom Validation Attribute you must also inherit and implement IClientValidatable. See the following links for more information.
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3
I don't know what your requirements are for your validation , but jQuery validate plugin
should handle it. It validates for a lot of common needs automatically (phone number, number, empty text, email) it is also very easy to add custom validation if needed.

How to change models editable atttribute based on a condition

Based on user credentials, I will allow users to edit a field or not on a Razor View.
So I currently have one model which I can do this for the properties I forbid:
[Editable(allowEdit=false)]
public string FirstName {get;set;}
but when I add the attribute whether or not a user has permission to edit it, they won't be able to. I cannot change the fields in Razor View either as we use a very different way of rendering model properties.
Any idea how can I overcome this problem?
You might want to create custom validation attribute and use that, in it you can inject your boolean and check and make it conditional (in C#).
The better option is to use Fluent Validation - its much easier to work with in these cases, when you need conditional validation. Also it will keep your models cleaner.
So if you can - use Fluent validation, if not, just define your own property and control it in your code including all conditions. Examples and links to libraries are here
Here is another option for you - complete library built with aim to easy the work you trying to achieve : http://foolproof.codeplex.com/
Hope this helps

Making good use of ASP.NET MVC DataAnnotations with separate assemblies

Let's say that I have a Domain assembly that describes the domain model, and it has a class called product:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
I have also another assembly that is the web application running with this domain model. Now I want to create a form to create new products and have some validation on the attributes. The easiest way to do this is to use DataAnnotations on the class. However this results in that the domain model now contains metadata about form validation, which is not a very clear separation of concerns.
It is possible to have the MetadataType attribute for the class but I see this as no better. Suddenly your domain model class has a dependency on the form validation metada class.
Another way is to create a CreateProductForm class and add the required attributes there, and do mapping between the classes. However this creates some overhead as you need to maintain these classes seperately and changes in one might break the other. It might be desirable in some scenarios to do that, but in some others it might just create extra work (imagine that you have an Address class, for example).
UPDATE: some people have suggested that I use AutoMapper for this, which I'm already aware of. AutoMapper just makes mapping simpler and easier, does not actually solve the problem of having to maintain two separate classes which will be almost identical. My preference would be to only create the form classes when there is a distinct need for it.
Is there a straightforward to declare the annotations within the web assembly, without creating unnecessary dependencies for the domain assembly?
If you don't want to introduce coupling between your domain model and your views, you should go for the CreateProductForm class way.
Depending on your project size/requirements, you're going to have to separate your view model from your domain sooner or later. Suppose you're using the DisplayName attribute : are you going to tag your domain entities ?
Using a tool like AutoMapper simplifies greatly the mapping process.
Why wouldn't you have DataAnnotations on your domain classes. If there is something that is Required, then I think it's perfectly valid to mark it as required in the domain.
Other DataAnnotations such as StringLength, Range etc, all to me perfectly valid things to decorate your domain entities with.
Implementing IValidableObject is also a perfectly acceptable thing for domain object to do IMHO.
I wouldn't go putting UI stuff on them such as UIHint though or annoations describing the formatting of the property. That would be bad.
Normally I avoid displaying domain classes on the user interface, and use ViewModel classes with a mapping tool such as AutoMapper etc to map from one to the other. The ViewModel class has the annoations of the domain class with perhaps additional UI specific annotations.
As mathieu and XHalent state you should use a CreateProductForm (or a CreateProductFormViewModel) along with Automapper and create attribues that automap the model to the viewmodel for the action.
That way all the form validation goes on your view model and all the data validation (related to the database) goes in your domain model.
In Silverlight and WPF it is called the MVVM pattern and a lot of people who do asp.net mvc recommend it.
In my current project I am also using it with Automapper. All my views have an associated view model that is a flattened version of the domain model specific to that view.
I think this was the example I used (It's the one I still have bookmarked anyway. but this one linked in the first one seems better.)
Using the attribute means that you return the domain object from your action in the controller and the automap attribute maps the domain object to your viewmodel automatically.
Doing this should give you the seperation you are looking for.

Building a forms system using DDD

i'm building a form managment system, thats is, the system will contain many forms, will save them, and perform logic on them, I want to do it using the DDD approach.
I want to support easy form layout later on using ASP.NET MVC, so far i see the domain like this:
I'll have a base form entity, which should(for now) have a name, fields(and theire values) and validation logic.
My questions are:
How should i write the field valueobject using generics? i cant seem to figure it out..
Should i encapsulate the validation logic inside the form or do it using the specification pattern?
How should i write the field valueobject using generics? i cant seem to figure it out.
Too vague question. Specify your context a bit - what kind of value objects you are trying to define, why exactly you need generics etc.
Should i encapsulate the validation logic inside the form or do it using the specification pattern?
Validation logic goes where it has to go. Domain validation logic should be encapsulated in specs, but that's not mandatory. Main thing - you should be able to figure out and understand applied validation when looking at source code of domain object class definition.
Apart from your vague descriptions, dealing with forms is a problem that is inherently not well suited to DDD. What kind of an object model can you build from a flat list of options?
Of course you will need validation logic that is specific to the form in use, but simple OO Design will get you far enough here, I don't see where DDD will buy you something.
As a side note, check out Document Databases, they might be better suited for your task than a sophisticated domain model stored in an ObjectDb or a relational database.

Categories