MyFluent - A Validation Framework using .Net Generics and Lambda Expressions (Fluent paradigm)

Purpose

Generics and Lambda expressions can be harnessed (in the Fluent Paradigm) for building a validation framework. MyFluent is my implementation of such a validation framework.

The source code is available free for download and you can build and add your own Rules and extend the framework.

Implementation

The Set<T, TProperty> is the base class for RuleSet<T, TProperty> and ConditionSet<T, TProperty>.

RuleSet<T, TProperty> contains the rules that can be applied.

ConditionSet<T, TProperty> contains the RuleSets that are to be applied if the Condition is true. It also holds the Condition specified as Func<TProperty, bool> .

In the RuleBuilder<T>, RuleSets and ConditionSets are stored in a static List<Set<T, object>> sets variable.

In the Validate method of the Validator<T>, the RuleSets and ConditionSets from the sets variable are evaluated against the instance of the object to validate.

BaseValidator<TValidator, T> creates a singleton instance of the validator, which is then re-used.

The MVC Model validation (client-side) is done by generating jQuery rules by the helper (MyFluentClientValidation). The rules hook into the jQuery validation plug-in.

The following built-in Rules are available:

rules-mvc-model-validation.jpg

* To be used in server-side validation for creating custom validations.

** To be used in MVC Model validation for creating custom validations.

The following class diagram explains the framework:

MyFluent_Framework.jpg

Usage

Server side validation

Suppose we had to validate an object of class ObjectToValidate which contains a complex object Employee.

Server-side-validation.jpg

First, add a reference to MyFluent.dll. Then create a validator (SampleValidator) and put the Rules in the constructor. 

  1. using MyFluent;  
  2.   
  3. public class SampleValidator : BaseValidator<SampleValidator, ObjectToValidate>  
  4. {  
  5.     public SampleValidator()  
  6.     {  
  7.         RuleFor(obj => obj.Employee)  
  8.             .NotNull("Employee cannot be null");  
  9.   
  10.         If(obj => obj.Employee.Language, language => language == Language.Bengali)  
  11.             .ConditionRuleFor(obj => obj.Employee.Name)  
  12.                 .NotNullOrEmpty("Name not null or empty")  
  13.                 .IsAlpha(@"\u0985-\u09E3\s""Employee name not Bengali letters with spaces")  
  14.                 .Matches(@"^[\u0985-\u09E3\s]+$""Employee name not Bengali letters with spaces")  
  15.             .ConditionRuleFor(obj => obj.Employee.Message)  
  16.                 .IsAlpha(@"\u0985-\u09E3\s""Employee message not Bengali letters with spaces");  
  17.   
  18.         If(obj => obj.Employee.Language, language => language == Language.English)  
  19.             .ConditionRuleFor(obj => obj.Employee.Name)  
  20.                 .NotNullOrEmpty("Name not null or empty")  
  21.                 .IsAlpha(@"a-zA-Z\s""Employee name not English letters with spaces")  
  22.                 .Matches("^[a-zA-Z ]+""Employee name not English letters with spaces")  
  23.             .ConditionRuleFor(obj => obj.Employee.Message)  
  24.                 .IsAlpha(@"a-zA-Z\s""Employee message not English letters with spaces");  
  25.   
  26.         RuleFor(obj => obj.Employee.JobTypes)  
  27.             .NotNull("Employee Job types cannot be null")  
  28.             .Required(jobTypes => jobTypes.Count > 0, "Employee requires at least one Job type");  
  29.   
  30.         RuleFor(obj => obj.Employee.CrediCardNo)  
  31.             .CreditCard("Invalid credit card no");  
  32.   
  33.         RuleFor(obj => obj.Employee.Email)  
  34.             .Email("Invalid email address");  
  35.     }  
  36. }  

After we have created the validator we can do the validation as shown below:
 

  1. static void Main(string[] args)  
  2. {  
  3.     ObjectToValidate objToValidate = new ObjectToValidate();  
  4.   
  5.     objToValidate.Employee = new Employee  
  6.     {  
  7.         Language = TestMyFluent.Language.English,  
  8.         //Language = TestMyFluent.Language.Bengali,  
  9.         Name = "Shantanu",  
  10.         //Name = "ফোটোস",  
  11.         //CrediCardNo = "****************",  
  12.         CrediCardNo = "5213291336202060",  
  13.         Email = "shantanu@@hotmail.com",  
  14.         //Message = "হ্যালো à¦«à§‹à¦Ÿà§‹à¦¸"  
  15.         Message = "Hello World",  
  16.         //JobTypes = new List<JobType>{ JobType.IT }  
  17.         JobTypes = new List<JobType> {}  
  18.     };  
  19.   
  20.     ValidationResult result = SampleValidator.Validate(objToValidate);  
  21. }  

ASP .NET MVC Model validation - client side

ASP.NET-MVC-Model-validation-client-side.jpg

MyFluent provides an HtmlHelper to generate jQuery rules (based on Rules specified on the Model in the validator) and wire up the form submit.

Add references to MyFluent.dll and MyFluent.Mvc.dll to get the helper and the MvcBaseValidator<TValidator, T>.
E.g.:

Model

register-model.jpg

Create the validator for the Model.

 
  1. using MyFluent.Mvc;  
  2.    
  3.     public class RegisterValidator : MvcBaseValidator<RegisterValidator, MvcApplication1.Models.RegisterModel>  
  4.     {  
  5.         public RegisterValidator()  
  6.         {  
  7.             RuleFor(m => m.UserName)  
  8.                .NotNullOrEmpty("User name cannot be null or empty")  
  9.                .Matches(@"^[a-zA-Z0-9]+$""User name should only contain letters and numbers");  
  10.    
  11.             RuleFor(m => m.Email)  
  12.                 .NotNullOrEmpty("Email cannot be null or empty")  
  13.                 .Email("Not a valid email address");  
  14.    
  15.             RuleFor(m => m.Password)  
  16.                 .NotNullOrEmpty("Password cannot be null or empty")  
  17.                 .JQueryRequired("UserNameNotInPassword""User name cannot be a part of the password");  
  18.    
  19.             RuleFor(m => m.ConfirmPassword)  
  20.                 .NotNullOrEmpty("Confirm password cannot be null or empty")  
  21.                 .JQueryRequired("PasswordAndConfirmAreSame""Password and confirm are not the same");  
  22.         }  
  23.     }  

Then in the view (Register.cshtml),
 

  1. @model MvcApplication1.Models.RegisterModel  
  2. @using MvcApplication1.Validators;  
  3.    
  4. @{  
  5.     ViewBag.Title = "Register";  
  6. }  
  7.    
  8. <h2>Create a New Account</h2>  
  9. <p>  
  10.     Use the following form to create a new account.  
  11. </p>   
  12. @*Include jQuery and jQuery validation plug-in*@  
  13.   
  14. <script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>  
  15. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>  
  16.    
  17. <script type="text/javascript">  
  18.     function UserNameNotInPassword(password) {  
  19.         var userName = $("#UserName").val();  
  20.    
  21.         return password.indexOf(userName) == -1;  
  22.     }  
  23.    
  24.     function PasswordAndConfirmAreSame(confirmPassword) {  
  25.         var password = $("#Password").val();  
  26.    
  27.         return password == confirmPassword;  
  28.     }  
  29.  </script>  
  30.    
  31. @*Call the helper*@  
  32. @Html.MyFluentClientValidation(RegisterValidator.GetValidator())  
  33.    
  34. @using (Html.BeginForm())  
  35. {  
  36.     @Html.ValidationSummary(true"Account creation was unsuccessful. Please correct the errors and try again.")  
  37.     <div>  
  38.         <fieldset>  
  39.             <legend>Account Information</legend>  
  40.    
  41.             <div class="editor-label">  
  42.                 @Html.LabelFor(m => m.UserName)  
  43.             </div>  
  44.             <div class="editor-field">  
  45.                 @Html.TextBoxFor(m => m.UserName)  
  46.                 @Html.ValidationMessageFor(m => m.UserName)  
  47.             </div>  
  48.    
  49.             <div class="editor-label">  
  50.                 @Html.LabelFor(m => m.Email)  
  51.             </div>  
  52.             <div class="editor-field">  
  53.                 @Html.TextBoxFor(m => m.Email)  
  54.                 @Html.ValidationMessageFor(m => m.Email)  
  55.             </div>  
  56.    
  57.             <div class="editor-label">  
  58.                 @Html.LabelFor(m => m.Password)  
  59.             </div>  
  60.             <div class="editor-field">  
  61.                 @Html.PasswordFor(m => m.Password)  
  62.                 @Html.ValidationMessageFor(m => m.Password)  
  63.             </div>  
  64.    
  65.             <div class="editor-label">  
  66.                 @Html.LabelFor(m => m.ConfirmPassword)  
  67.             </div>  
  68.             <div class="editor-field">  
  69.                 @Html.PasswordFor(m => m.ConfirmPassword)  
  70.                 @Html.ValidationMessageFor(m => m.ConfirmPassword)  
  71.             </div>  
  72.    
  73.             <p>  
  74.                 <input type="submit" value="Register" />  
  75.             </p>  
  76.         </fieldset>  
  77.     </div>  
  78. }  

You can do custom validations using the JQueryRequired rule where you specify the function which will be called as a part of validation of the property. Eg. UserNameNotInPassword is a custom validation function which will be called whenever the Password validation occurs. This function must return true or false.

Conditional rules are not available in MVC Model validation.

You can attach the default submit handler which automatically triggers the jQuery validate method. Or you can create your own custom handler.

Screen shot:
 Register Page validation

 
Note: You can take advantage of some multi-lingual Rules which require the Unicode range set to be specified. The Unicode chart gives the range set.

http://www.ssec.wisc.edu/%7Etomw/java/unicode.html