Skip to main content

Client side Validation for data driven view engine

The prerequisite for this is to have a designed database driven view engine. This can be a good guidance to implement DB driven view engine Data Driven Custom View Engine in ASP.NET MVC (http://www.dotnetcurry.com/aspnet-mvc/946/data-driven-custom-view-engine-aspnet-mvc).

If we talk about the concept then we can say for DB driven view engine a dynamic form/screen table would require along with the associate attribute set for controls. The controls, Attribute set can have constraints like Required, MaxLength, RegEx etc. similar to available DataAnnotation implementation, just that it has to come through DB.

The jQuery unobtrusive validation is all about adding certain HTML 5 data attributes. So, if we can find rules of the controls (required, max length etc) and set it to HTML attribute from view engine then we are done.

While designing DB driven view engine, there should be a place where we need to loop through available controls to identify it's type and write as HTML/element. A common attribute set can be applied to all controls including the validation rule.

This  would allow us to get key value validation attributes.

 /// <summary>  
 /// Gets the unobtrusive validation attributes.  
 /// </summary>  
 /// <param name="control">The field for dynamic controls.</param>  
 /// <returns>Validation attributes wrapped in Dictionary.</returns>  
 private IDictionary<string, object> GetUnobtrusiveValidationAttributes(AttributeSet control)  
 {  
      IDictionary<string, object> validationAttribs = new Dictionary<string, object>();  
      ModelMetadata metaData = ModelMetadata.FromStringExpression(GetFieldName(control), Helper.ViewData);  
      var clientValidator = new AttributeSetModelValidatorProvider(metaData, ControllerContext,  
           new MaxLengthAttribute(), // Dummy attribute passed  
           control);  
      UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientValidator.GetClientValidationRules(), validationAttribs);  
      return validationAttribs;  
 }  

The AttributeSetModelValidatorProvider is a custom class designed to get the validation configuration. The class inherits from DataAnnotationsModelValidator, there are certain parameters that need to be passed for initialization that is why few dummy data are passed. In general, it generates single validation rule but in our case, it has to be multiple rules.


The GetValidationAttributes method transforms into dictionary object. That dictionary object then can be applied to MVC controls.

The implementation of custom class:

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel.DataAnnotations;  
 using System.Web.Mvc;  
 /// <summary>  
 /// Data annotation model provider for dynamic controls  
 /// </summary>  
 public class AttributeSetModelValidatorProvider  
 : DataAnnotationsModelValidator  
 {  
   /// <summary>  
   /// The dynamic control for generating validation rules.  
   /// </summary>  
   private readonly AttributeSet Control;  
   /// <summary>  
   /// Initializes a new instance of the <see cref="AttributeSetModelValidatorProvider"/> class.  
   /// </summary>  
   /// <param name="metadata">The metadata.</param>  
   /// <param name="context">The context.</param>  
   /// <param name="attribute">The attribute.</param>  
   /// <param name="control">The dynamic control.</param>  
   public AttributeSetModelValidatorProvider(ModelMetadata metadata, ControllerContext context,  
     ValidationAttribute attribute, AttributeSet control)  
     : base(metadata, context, attribute)  
   {  
     Control = control;  
   }  
   /// <summary>  
   /// Retrieves a collection of client validation rules.  
   /// </summary>  
   /// <returns>  
   /// A collection of client validation rules.  
   /// </returns>  
   public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()  
   {  
     var validationRules = new List<ModelClientValidationRule>();  
     #region " Different client side validation rule for dynamic controls "  
     if (Control.IsFieldValueRequired)  
     {  
       validationRules.Add(new ModelClientValidationRequiredRule(  
         String.Format("{0} cannot be empty.", Control.DisplayLabel)));  
     }  
     if (!String.IsNullOrEmpty(Control.ValidationRegEx))  
     {  
       validationRules.Add(new ModelClientValidationRegexRule(String.Format(  
         "Not a valid {0}", Control.DisplayLabel), Control.ValidationRegEx));  
     }  
     if (Control.MaxLength.HasValue && Control.MaxLength.Value > 0)  
     {  
       validationRules.Add(new ModelClientValidationMaxLengthRule(String.Format(  
         "{0} is having {1} allowed characters.", Control.DisplayLabel, Control.MaxLength), Control.MaxLength.Value));  
     }  
     if (Control.FieldName.ToLower().Contains("email"))  
     {  
       validationRules.Add(new ModelClientValidationRule()  
       {  
         ValidationType = "email",  
         ErrorMessage = "E Mail id is not valid."  
       });  
     }  
     ModelClientValidationRule dataType;  
     if (TryGettingTypeValidationRule(Control, out dataType))  
     {  
       validationRules.Add(dataType);  
     }  
     #endregion " Different client side validation rule for dynamic controls "  
     return validationRules;  
   }  
   /// <summary>  
   /// Try getting validation rule for dynamic control.  
   /// </summary>  
   /// <param name="dataField">The data field for dynamic control.</param>  
   /// <param name="dataTypeValidationRule">The data type validation rule.</param>  
   /// <returns>True, if Validation rule exist for dynamic control</returns>  
   private static bool TryGettingTypeValidationRule(AttributeSet dataField,  
     out ModelClientValidationRule dataTypeValidationRule)  
   {  
     dataTypeValidationRule = null;  
     var isSucess = false;  
     // Helper for creation object for validation rule  
     Func<string, string, ModelClientValidationRule> getValidationRule = (validationType, messageFormat) =>  
     {  
       return new ModelClientValidationRule  
       {  
         ValidationType = validationType,  
         ErrorMessage = String.Format(messageFormat, dataField.DisplayLabel)  
       };  
     };  
     // Rules based on data annotation and jQuery Unobtrusive validation  
     switch (dataField.FieldType.DisplayType)  
     {  
       case DbFieldType.ShortTime:  
       case DbFieldType.DateTime:  
       case DbFieldType.ShortDate:  
         dataTypeValidationRule = getValidationRule("date", "The field {0} must be a date.");  
         isSucess = true;  
         break;  
       case DbFieldType.Integer:  
       case DbFieldType.Decimal:  
       case DbFieldType.Money:  
       case DbFieldType.Percentage:  
         dataTypeValidationRule = getValidationRule("number", "The field {0} must be a number.");  
         isSucess = true;  
         break;  
     }  
     // Avoid type check for masked text boxes  
     if (!String.IsNullOrEmpty(dataField.MaskedTextFormat))  
     {  
       isSucess = false;  
     }  
     return isSucess;  
   }  
 }  


The implementation is really simple, has to override GetClientValidationRules function which would return a list of ModelClientValidationRule. This list can have multiple rules like ModelClientValidationRegexRuleModelClientValidationMaxLengthRule, etc. which are built in classes from MVC.

Popular posts from this blog

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

LDAP with ASPNet Core Identity in MVC Core

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

AspNet Identity Core is a new offering from Microsoft in replacement of AspNet Identity for managing users.

In this tutorial, we would be looking for implementing LDAP with AspNet Identity Core to allow users to be able to log in through AD or AspNet Identity Core members.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functiona…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…