What advantage has Fluent Validation vs the default .NET Data Annotations - asp.net-mvc

What advantage does the FluentValidation library have over the .NET System.ComponentModel.DataAnnotations?
Does it offer more flexible validation as it is not annotated (static field validation) on the property like validating a property depending on another's property value?

I'm not sure about data annotations but we've used FluentValidation for validation part in business logic. And easy integrating with ASP.NET MVC is nice bonus :)
It supports a lot of built-in rules, error messages localization, using object data in error messages, custom validation methods, conditional validation - applying some rules if object data matches a condition, rule sets - apply named set of rules, validation of aggregated objects and collections - and property names would be compatible with ASP.NET MVC property names and so on.

Related

Data annotation validation for multiple model properties

I'm currently using MVC data annotations for validating my form and it looks quite easy.
Now, I have a particular situation:
IF(checkbox1value = checked), then validate if textbox is not empty. If textbox is empty, then show validation error message.
How do I do this? Both checkbox and textbox are available as my model properties (bool and string respectively).
Is it possible to do this via a custom validation?
You can use a custom validator or IValidateableOject
There's a good explanation of both options here.
From the link.
If you need to support client validation, then a custom validator is what you want.
If your validation is strictly server side and you want to validate a number of business rules at once then use IValidateableObject.
I had to switch to Foolproof validation, which offered this functionality through it's RequiredIfTrue validator. I also really liked Fluent Validation since it was really flexible, and would also easily offer this functionality. Foolproof client-side support is provided for each of it's validators, where the boundary between client and server validation with Fluent Validation is not as easily distinguishable.

ASP.NET MVC - Dynamic RegEx Validator

In our application our customers are allowed to define a couple of reference fields, and the validation for these reference fields by way of a regular expression. The Validation Regex is saved into our database.
What is the best way to apply this regex as validation for an MVC text box field?
In addition to checking server-side when the value's submitted, you can use remote validation which would create a round-trip to test the current value against logic stored on the server (or in this case in a database).
Have a look at the RemoteAttribute and that MSDN article above (which includes an example).

Entity Framework: Where to put business logic that that ASP.NET ModelState is populated?

I have a site that uses Entity Framework for data persistence.
I have used the buddy class system on a number of Entities to flag what fields are required using data annotations.
ASP.NET MVC and its ModelState work great with this out of the box.
My question is, I have some validation that is a little more involved -
Is there a way I can include this business logic in the buddy class in such a way that the ModelState is populated correctly?
An example of this would be
If field X is of one value, then Field Y is required.
The logic may get more complex than this.
Thanks,
This could be achieved by writing custom validator attributes. But personally I prefer the FluentValidation.NET framework instead of data annotations as it provides a more concise and easier way to express custom validation logic even in complex scenarios.
You should make the entities themselves implement IValidatableObject, then use an iterator to yield return a ValidationResult for each error.
Alternatively, you can make a custom class-level ValidationAttribute and apply it to the buddy class.

ASP.NET MVC 2 Validation: Metadatatype can't be added to standard POCO CLR classes - what's an alternative?

I am using Entity Framework and generating my POCO classes via T4 - these classes inherit from nothing and are very plain and simple (created via template in vs 2010)
I tried using the Metadatatype Attribute so I could create a buddy class but when I did this I no longer was able to see my properties... if I removed the attribute! the properties appeared.
Anyway, searching deeper I found this statement from Microsoft
The associated class must be used with EDM or LINQ-to-SQL models because CLR types cannot mark existing properties with new attributes. If you are working with CLR objects directly, sometimes referred to as Plain Old CLR Object (POCO) types, you can apply the attributes directly to the model
So it appears it doesn't work. Anyway it's difficult for me to insert my Data Annotation on the MODEL itself because it's created via T4 hence if I edit it and then re-run the tool it will remove all my changes.
There is a pretty strong consensus around SO and the MVC blogosphere that you shouldn't annotate your business/crud/domain classes with attributes. Not only is your entire MVC stack becoming dependent upon your business/database classes but you'll quickly end up with multiple context scenarios ( same Model, different validation rules ) that are impossible to validate with just a single model.
Use separate view models for your screens, annotate those.
Based on your comment: "Data Annotation on the MODEL itself because its created via T4 hence"
What I'm trying to say is put your dataannotations on your viewmodels, leave your POCO models alone.

Combine DataAnnotations Validation with complex business rules

I understand annotating class properties with the basic required and minimum length and getting all the benefits of the asp.net mvc server side and client side validation.
However does anyone have a link that shows how you combine this 'base' validation with more complex business rules. How would I run business rule functions, such as for example, has the customer ordered anything in the last year (database hit required) and still use the same DataAnnotation and mvc validation plumbing?
Goal : Don't want two ways of generating and outputting validation methods.
From http://msdn.microsoft.com/en-us/library/dd901590%28VS.95%29.aspx:
To create customized validation checks, you can either create a class that derives from the ValidationAttribute class or create a method that performs the validation check and reference that method when applying the CustomValidationAttribute to the data member. When you create a class that derives from ValidationAttribute, override the IsValid method to provide the logic for your customized validation check.
There appears to be example code there.
Data Annotation run before your action is invoked. Then, regardless whether the validation succeded or not, the action is still called. If the DA detected invalid data, your ModelState will be invalid.
Once here, you can still do any validation you want, for your business rules, as you would normally do without the data annotation, if you want to. In your action, you can add errors to the ModelState even if the Data Annotation validation passed.
In this case, you add your errors with ModelState.addError, and those errors are added to any error provided by the DA. So in your View it doesn't matter where the error comes from.
Or, if your rules are general, you can write your own annotation tags. The Data Annotation thing is distributed with its source, so you have full control on it.
You could use VAB (Application Validation Block) from the Enterprise Library 5 of Microsoft that actually based on the DataAnnotations class but u do your complex bussiness logic very easily through configuration...
i'd suggest you check it out...
Have a look at following article, where you can use DataAnnotations Multiple Times On Same Field, Compare N number of properties and N number of values....
http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx

Resources