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.
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:
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.
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
Post a Comment