This project is read-only.

An important part of any data-driven application is ensuring data consistency and handling errors when they occur. Ensuring data consistency requires a combination of data input. Validation means ensuring that any user input meets the application's expectations for what that data should contain.
We use Microsoft Validation Application Block to validate inputs of the user. Make sure that EntLib 3.1 (or any other version) is properly installed.

Create string length validator for Contact.FirstName and Contact.LastName; adds a Regex Validator for Contact.Email as shown on the figure below


Once the validation rules are created, right click on the util folder and add a class. Name the class Utility and write the following code:

public class Utility
    public static ValidationResults ValidateData<TEntity>(TEntity entity) where TEntity : AbstractBaseData
        //Validate the data
        ValidationResults results = Validation.Validate<TEntity>(entity);

        //Clearing the error list

        if (results.IsValid) return results;

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

The code simply validates a specific data passed as argument and fills the internal per-property error message dictionary. The dictionary will be used to display broken rules to the user.

The next step is, obviously, to validate the contact object built by the user before storing it. In the SaveView code-behid, edit the click event of the save button and update the code as shown below:

private void btSave_Click(object sender, EventArgs e)
    //Validation the Data
    SaveViewData saveView = this.GetSessionData(typeof(SaveViewData).Name) as SaveViewData;
    ValidationResults results = Utility.ValidateData<Contact>(saveView.Contact);

    //set the source of the errorProvider
    epSaveContact.DataSource = contactBindingSource;

    if (!results.IsValid) return;

    //Initializing datasource
    epSaveContact.DataSource = null;

    //Invoke a specific action
    this.InvokeController(typeof(SaveController).Name, ApplicationData.SaveAction);

The contact data is validated using the static ValidateData methods written in the Utility class. If the result is not valid the process is stopped by the return instruction and broken rules.

Run the application and try to create an invalid input contact:


Last edited Jun 22, 2009 at 11:16 PM by koossery, version 2


No comments yet.