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 ModelClientValidationRegexRule, ModelClientValidationMaxLengthRule, etc. which are built in classes from MVC.

Comments

Popular posts from this blog

Using Redis distributed cache in dotnet core with helper extension methods

Redis cache is out process cache provider for a distributed environment. It is popular in Azure Cloud solution, but it also has a standalone application to operate upon in case of small enterprises application. How to install Redis Cache on a local machine? Redis can be used as a local cache server too on our local machines. At first install, Chocolatey https://chocolatey.org/ , to make installation of Redis easy. Also, the version under Chocolatey supports more commands and compatible with Official Cache package from Microsoft. After Chocolatey installation hit choco install redis-64 . Once the installation is done, we can start the server by running redis-server . Distributed Cache package and registration dotnet core provides IDistributedCache interface which can be overrided with our own implementation. That is one of the beauties of dotnet core, having DI implementation at heart of framework. There is already nuget package available to override IDistributedCache i...

Kendo MVC Grid DataSourceRequest with AutoMapper - Advance

The actual process to make DataSourceRequest compatible with AutoMapper was explained in my previous post  Kendo MVC Grid DataSourceRequest with AutoMapper , where we had created custom model binder attribute and in that property names were changed as data models. In this post we will be looking into using AutoMapper's Queryable extension to retrieve the results based on selected columns. When  Mapper.Map<RoleViewModel>(data)  is called it retrieves all column values from table. The Queryable extension provides a way to retrieve only selected columns from table. In this particular case based on properties of  RoleViewModel . The previous approach that we implemented is perfect as far as this article ( 3 Tips for Using Telerik Data Access and AutoMapper ) is concern about performance where it states: While this functionality allows you avoid writing explicit projection in to your LINQ query it has the same fatal flaw as doing so - it prevents the qu...

C# Response files

Response files are similar to batch files, having some specific instruction. On execution they perform some predefined task based on instruction. Response file contains instruction to compile programs. If we have to build complex program through command line then response files are really helpful in development process. rsp is an extension for response files. By default, csc.rsp file exists under "Framework" folder Ex: C:\Windows\Microsoft.NET\Framework\v4.0.30319. csc.rsp contains long list of system references (dlls). Some contents under csc.rsp # Reference the common Framework libraries /r:Accessibility.dll /r:Microsoft.CSharp.dll /r:System.Configuration.dll /r:System.Configuration.Install.dll /r:System.Core.dll /r:System.Data.dll /r:System.Data.DataSetExtensions.dll /r:System.Data.Linq.dll .......... In same way we can have our own response file defined which might include some third party dll. Let's see an example. Suppose we have to create an appli...

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 ...

Blazor 0.5.0 Interop JavaScript from C# and C# to JavaScript call

Blazor provides two-way communication from JS to C# and C# to JS which is called Interop. The version upgrade to Blazor 0.5.0 changed the approach in interactions between cshtml and JS files. The newer version simplifies JS calling by avoiding pre-registration of JS function. In this article, we would see how to call a JS method by passing multiple parameters from cshtml and parameterized call from JS to cshtml. The scenario that is used in this article has a Kendo AutoComplete to search book and populate information based on the selection. An example of a call to JS from cshtml await JSRuntime.Current.InvokeAsync<string>( "searchBook.Init", "#SearchTitle", new DotNetObjectRef(this)); Takeaways from the above example: - JSRuntime.Current give environment to execute out-process JS. - InvokeAsync is a function that would allow executing the JS function. - The searchBook.Init is a JS function call, we would see it in details in the second sec...

MongoDB navigation property or making it behave as ORM in .Net

This is an implementation to make models to have  navigation properties work like ORM does for us. What actually happens in ORM to make navigation properties work? Entity Framework has proxy classes implementation to allow lazy loading and eager loading implementation. While creating proxy classes it also changes definitions for actual classes to make navigation properties work to get values based on Model's for navigation properties. Most of ORMs work in same fashion like Telerik DataAccess has enhancer tool which changes class definition at compile time to enable navigation properties. In this implementation, we would retain the original class but we would have extension methods to allow initializing properties to have navigation proprieties work. Let's first create desire model on which we need to implement. I am picking up simple one-to-many relationship example from Person to Address. public class Person { public int PersonId { get; set; } ...

Trim text in MVC Core through Model Binder

Trimming text can be done on client side codes, but I believe it is most suitable on MVC Model Binder since it would be at one place on infrastructure level which would be free from any manual intervention of developer. This would allow every post request to be processed and converted to a trimmed string. Let us start by creating Model binder using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Threading.Tasks; public class TrimmingModelBinder : IModelBinder { private readonly IModelBinder FallbackBinder; public TrimmingModelBinder(IModelBinder fallbackBinder) { FallbackBinder = fallbackBinder ?? throw new ArgumentNullException(nameof(fallbackBinder)); } public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var valueProviderResult = bindingContext.ValueProvider.GetValue(bin...

Kendo MVC Grid DataSourceRequest with AutoMapper

Kendo Grid does not work directly with AutoMapper but could be managed by simple trick using mapping through ToDataSourceResult. The solution works fine until different filters are applied. The problems occurs because passed filters refer to view model properties where as database model properties are required after AutoMapper is implemented. So, the plan is to intercept DataSourceRequest  and modify names based on database model. To do that we are going to create implementation of  CustomModelBinderAttribute to catch calls and have our own implementation of DataSourceRequestAttribute from Kendo MVC. I will be using same source code from Kendo but will replace column names for different criteria for sort, filters, group etc. Let's first look into how that will be implemented. public ActionResult GetRoles([MyDataSourceRequest(GridId.RolesUserGrid)] DataSourceRequest request) { if (request == null) { throw new Argume...

Channel, ChannelReader and ChannelWriter to manage data streams in multi-threading environment

I came across Channel class while working with SignalR which looks really interesting. By looking into NuGet packages ( https://www.nuget.org/packages/System.Threading.Channels ), it seems just 4 months old. The Channel class provides infrastructure to have multiple reads and write simuletensely through it's Reader and Writer properties. This is where it is handy in case of SignalR where data streaming needs to be done but is not just limited to that but wherever something needs to be read/write/combination of both in a multi-threading environment. In my case with SignalR, I had to stream stock data at a regular interval of time. public ChannelReader<StockData> StreamStock() { var channel = Channel.CreateUnbounded<StockData>(); _stockManager.OnStockData = stockData => { channel.Writer.TryWrite(stockData); }; return channel.Reader; } The SignalR keeps return type of ChannelReader<StockData> open so that whatev...

Dependency Injection through XML configuration and XML transformation through SlowCheetah

Dependency Injection (DI) is a design pattern to change definition by substituting object without changing code for the application. The most popular DI type is to construct classes based on certain interface and pass actual object on constructor level. What are we trying to do? We will be looking into a way to achieve dependency injection through XML configuration based on  build selection . The implemented classes derived through interface will get switched based on build selection. Where to use it? I really hate making dependencies with something specific which can be changed later on. In my case, Azure environment. I believe Azure is more like a platform where we can host the application rather then integrating the application with Azure. What if client decided to switch to other hosting environment, in that case we got to change every piece of code wherever Azure SDKs are referred. The above one is merely an example. We can use this approach on many other item as wel...