Performing validation using MSVAB

Due to the fact that the validation logic is directly written in the set part of properties, the validation is performed every time a particular value is set, even when it’s not required. The fact that the validation logic is directly written in the set part makes the application to be less maintainable.
Instead of configuring validation logic directly in the set part of property we can configure those rules in an external file and validate Data only when it’s required.

The Enterprise Library Validation Application Block provides a library of classes called validator, which supplies the code for validating .NET Framework data types. For example, one validator checks that strings are not null and another validator ensures that a number falls within a specified range. You can use a Boolean AND or OR to create composite validators. You can also create groups of validators. A group of validators is called a rule set, although a rule set may contain as few as a single validator. A rule set is a way to validate a complex object or graph by composing different validators of different types and applying them to elements in the object graph. Examples of these elements include fields, properties, and nested objects.

You can check the link below to learn how to configure validation rule of an object
http://msdn.microsoft.com/en-us/library/cc309509.aspx

The listing 1 below shows the LoginViewData configuration

<type defaultRuleset="Default Rule" assemblyName="Koossery.MVCwin.Tuto, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
      name="Koossery.MVCwin.Tuto.App_Code.data.session.LoginViewData">
      <ruleset name="Default Rule">
        <properties>
          <property name="Login">
            <validator negated="false" messageTemplate="Login should not be null"
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Not Null Validator" />
            <validator lowerBound="2" lowerBoundType="Inclusive" upperBound="10"
              upperBoundType="Inclusive" negated="false" messageTemplate="Should not be null"
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="String Length Validator" />
          </property>
          <property name="Password">
            <validator negated="false" messageTemplate="Password should not be null"
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="Not Null Validator" />
            <validator lowerBound="2" lowerBoundType="Inclusive" upperBound="10"
              upperBoundType="Inclusive" negated="false" messageTemplate=""
              messageTemplateResourceName="" messageTemplateResourceType=""
              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
              name="String Length Validator" />
          </property>
        </properties>
      </ruleset>
    </type>


Displaying Errors with the IDataErrorInfo
MSVAB is used to validate objects. It provides the Validate<TEntity> method to validate a specific object and return the ValidationResults object. The validationResults object is a per-property error message dictionary. As long as all ViewData inherits from IDataErrorInfo we can then iterate through the ValidationResults property and fill the object level per-property error message dictionary.
The listing 2 shows Validate<TEntity> method

public static ValidationResults ValidateData<TEntity>(TEntity entity) where TEntity : AbstractBaseData
{
     //Validate the data
     ValidationResults results = Validation.Validate<TEntity>(entity);
            
     //Clearing the error list
     entity.ClearPropertyErrors();

     if (results.IsValid) return results;
                        
     //Copying errors messages            
     foreach (ValidationResult result in results)
     {                
          entity[result.Key] = result.Message;
     }            
     return results;
}

The ValidateData<TEntity> method validates a specific data using the MSVAB and copies the broken rules in the object level per-property error message dictionary.

The listing 3 shows how the validation is made at the LoginView

private void btLogin_Click(object sender, EventArgs e)
{
    string typeOfLoginViewData = typeof(LoginViewData).Name;
    LoginViewData loginViewData = this.GetSessionData(typeOfLoginViewData) as LoginViewData;

    //Validating the data
    ValidationResults results = Utility.ValidateData<LoginViewData>(loginViewData);

    epLoginView.DataSource = bsLoginViewData;

    //Is the data valid ?
    if (!results.IsValid) return ;

    //Invoking a specific action
    this.InvokeController(typeof(LoginController).Name, ApplicationData.LoginAction_Login);
}

Once the dictionary is filled all Data-bounded controls will be notified as shown in the figure below

ValidationResult.PNG

Last edited Jun 19, 2009 at 4:45 PM by mohamadou, version 8

Comments

No comments yet.