Use Fluent Validation for Creating a Sophisticated Data Validation Framework in ASP.NET MVC
Data validation is quite critical when it comes to usability and data integrity of any software or application. It helps in improving the quality of the data as well as ensuring the data consistency. Let's talk about utilizing Fluent Validation to make things easier.
Join the DZone community and get the full member experience.
Join For Freeagain, there is nothing wrong in data annotations as similar results can be accomplished by following that approach. but, too many annotations can make your model look quite ugly.
what is fluent validation?

using system;
using system.collections.generic;
using system.linq;
using system.web;
using fluentvalidation;
using fluentvalidation.attributes;
using fluentvalidation.results;
using system.componentmodel.dataannotations;
using efcodefirstmvcapplication.models;
namespace efcodefirstmvcapplication.models
{
public class product
{
public int id { get; set; }
public string prod_sku { get; set; }
public string prod_name { get; set; }
public datetime createdate { get; set; }
}
}
in order to implement fluentvalidation, we need to add a line to the global.asax file (in application _start method). this will hook up the fluentvalidation class library to the asp.net mvc 5 validation framework. we will call fluentvalidationmodelvalidatorprovider.configure() method inside the global.asax file like this:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
using system.web.optimization;
using system.web.routing;
using fluentvalidation.mvc;
namespace efcodefirstmvcapplication
{
public class mvcapplication : system.web.httpapplication
{
protected void application_start()
{
arearegistration.registerallareas();
filterconfig.registerglobalfilters(globalfilters.filters);
routeconfig.registerroutes(routetable.routes);
bundleconfig.registerbundles(bundletable.bundles);
// adding fluentvalidation
fluentvalidationmodelvalidatorprovider.configure();
}
}
}
now, we can start setting up the actual data validation. there are two ways of creating custom validators. the first is to create a custom property validator, the second is to make use of the custom method on abstractvalidator. let’s create a new class called "fluentproductvalidator" like this:
public class fluentproductvalidator : abstractvalidator<product>
{
public fluentproductvalidator()
{
}
}
next step is to add validation rules in the fluentproductvalidator class for “prod_sku” & "prod_name".
public class fluentproductvalidator : abstractvalidator<product>
{
public fluentproductvalidator()
{
rulefor(x => x.prod_sku).notempty().withmessage("sku is required");
rulefor(x => x.prod_name).notempty().withmessage("name is required");
}
}
our complete product model files looks like this:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using fluentvalidation;
using fluentvalidation.attributes;
using fluentvalidation.results;
using system.componentmodel.dataannotations;
using efcodefirstmvcapplication.models;
namespace efcodefirstmvcapplication.models
{
[validator(typeof(fluentproductvalidator))]
public class product
{
public int id { get; set; }
public string prod_sku { get; set; }
public string prod_name { get; set; }
public datetime createdate { get; set; }
public virtual icollection<productmanufacturermapping> productcategorymappings { get; set; }
}
public class fluentproductvalidator : abstractvalidator<product>
{
public fluentproductvalidator()
{
rulefor(x => x.prod_sku).notempty().withmessage("sku is required");
rulefor(x => x.prod_name).notempty().withmessage("name is required");
}
}
}
now, if we run the application and go to create or edit, we should see the validations like this:

we have successfully implemented the fluentvalidation in our asp.net mvc web application.
open-source .net projects like nopcommerce are using fluentvalidation for data validation
fluentvalidation is a very powerful validation framework that allows many features that regular componentmodel framework does not offer which is why a project like nopcommerce is using it in the official software. now the question is, how does fluent validation benefit projects like nopcommerce?
- fluent validation gives nopcommerce far more control over the validation rules
- nopcommerce project can make use of conditional validation which is quite easier as compared to data annotations
- it allows nopcommerce an option to separate all the validations from the view models
- unit testing is far easier as compared to data annotations
- fluent validation offers a better client-side validation support
- nopcommerce can be download here: http://www.nopcommerce.com/downloads.aspx
-
nopcommerce is also available in microsoft web app gallery:
https://www.microsoft.com/web/gallery/nopcommerce.aspx/en-us
let’s take a look at how nopcommerce is making use of fluentvalidation in the project
one of the most important things in an e-commerce business is customer data. in order to maintain quality data (i.e. customer information) in the database, it is critical to have strong data validation rules on the public store. nopcommerce makes the best use of fluent validation in this area. so, let’s look into "addressvalidator.cs" that can be found in this location:
nop.web\validators\common\addressvalidator.cs

here is the source code:
using fluentvalidation;
using fluentvalidation.results;
using nop.core.domain.common;
using nop.services.directory;
using nop.services.localization;
using nop.web.framework.validators;
using nop.web.models.common;
namespace nop.web.validators.common
{
public class addressvalidator : basenopvalidator<addressmodel>
{
public addressvalidator(ilocalizationservice localizationservice,
istateprovinceservice stateprovinceservice,
addresssettings addresssettings)
{
rulefor(x => x.firstname)
.notempty()
.withmessage(localizationservice.getresource("address.fields.firstname.required"));
rulefor(x => x.lastname)
.notempty()
.withmessage(localizationservice.getresource("address.fields.lastname.required"));
rulefor(x => x.email)
.notempty()
.withmessage(localizationservice.getresource("address.fields.email.required"));
rulefor(x => x.email)
.emailaddress()
.withmessage(localizationservice.getresource("common.wrongemail"));
if (addresssettings.countryenabled)
{
rulefor(x => x.countryid)
.notnull()
.withmessage(localizationservice.getresource("address.fields.country.required"));
rulefor(x => x.countryid)
.notequal(0)
.withmessage(localizationservice.getresource("address.fields.country.required"));
}
if (addresssettings.countryenabled && addresssettings.stateprovinceenabled)
{
custom(x =>
{
//does selected country has states?
var countryid = x.countryid.hasvalue ? x.countryid.value : 0;
var hasstates = stateprovinceservice.getstateprovincesbycountryid(countryid).count > 0;
if (hasstates)
{
//if yes, then ensure that state is selected
if (!x.stateprovinceid.hasvalue || x.stateprovinceid.value == 0)
{
return new validationfailure("stateprovinceid", localizationservice.getresource("address.fields.stateprovince.required"));
}
}
return null;
});
}
if (addresssettings.companyrequired && addresssettings.companyenabled)
{
rulefor(x => x.company).notempty().withmessage(localizationservice.getresource("account.fields.company.required"));
}
if (addresssettings.streetaddressrequired && addresssettings.streetaddressenabled)
{
rulefor(x => x.address1).notempty().withmessage(localizationservice.getresource("account.fields.streetaddress.required"));
}
if (addresssettings.streetaddress2required && addresssettings.streetaddress2enabled)
{
rulefor(x => x.address2).notempty().withmessage(localizationservice.getresource("account.fields.streetaddress2.required"));
}
if (addresssettings.zippostalcoderequired && addresssettings.zippostalcodeenabled)
{
rulefor(x => x.zippostalcode).notempty().withmessage(localizationservice.getresource("account.fields.zippostalcode.required"));
}
if (addresssettings.cityrequired && addresssettings.cityenabled)
{
rulefor(x => x.city).notempty().withmessage(localizationservice.getresource("account.fields.city.required"));
}
if (addresssettings.phonerequired && addresssettings.phoneenabled)
{
rulefor(x => x.phonenumber).notempty().withmessage(localizationservice.getresource("account.fields.phone.required"));
}
if (addresssettings.faxrequired && addresssettings.faxenabled)
{
rulefor(x => x.faxnumber).notempty().withmessage(localizationservice.getresource("account.fields.fax.required"));
}
}
}
}
all the validation rules in nopcommerce are making use of localization resource values so that, depending upon the selected language for public store, the validation messages can be shown. if we look closely to the source code (above), we will find that nopcommerce is using the "notempty" validator (in this case) instead of notnull validator. whereas, in queuedemailvalidator.cs, nopcommerce project is making use of "notnull() validator":

so, what is the difference between these two validators?
example:
how to change/update data validation message in nopcommerce?
rulefor(x => x.firstname)
.notempty()
.withmessage(localizationservice.getresource("address.fields.firstname.required"));
we should change/update it in the administration section (for each language): configuration > languages


option 2: an alternative method to change/update the validation method in nopcommerce is to update directly in the source code. this is not the cleanest approach as in future if you wish you update it again, you will have to change it in the source code. but, at the end of the day this method still works and get the job done.
rulefor(x => x.firstname)
.notempty()
.withmessage(localizationservice.getresource("address.fields.firstname.required"));
rulefor(x => x.firstname)
.notempty()
.withmessage("new hardcoded validation message here");
now, if we go to the nopcommerce public store (in account) and try to add the address without first name, we should see the updated message like this:

resources
Published at DZone with permission of Lavish Kumar. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments